View Single Post
Old 2022-02-05, 17:05   #7
newalex
 
Feb 2019

1610 Posts
Default

Quote:
Originally Posted by kruoli View Post
Would you mind sharing/PM'ing your program? I could run it on 1t digits I have. And maybe some other constants.
Yes, of course. But I am not sure if it would be suitable for you. It is written in Java and stores all digits in memory. So you need 1 Tb of RAM to run it for 1t. It can be fixed easily but need some work.
Here is the source code
Code:
import java.io.*;

public class PrimesInPi {

    public static void main(String[] args) throws IOException {
        FileReader fr = new FileReader("pi.txt");
        long piSize = 100000000000L;
        final int maxArraySize = 1000000000;
        int chunkSize = (piSize>maxArraySize) ? maxArraySize : (int) piSize;
        char[][] pi;
        pi = new char[(int) (piSize/chunkSize)][chunkSize];
        fr.read();
        fr.read();
        for (int i=0; i<piSize/chunkSize; i++) {
            fr.read(pi[i], 0, chunkSize);
        }
        fr.close();
        BufferedReader primesReader = new BufferedReader(new FileReader("primes.txt"));
        String prime = primesReader.readLine();
        FileWriter result = new FileWriter("output.txt");
        long pos = 0;
        int i=0, j=0;
        while (pos<piSize) {
            if (isCurrentPrime(pi, prime, i, j)) {
                result.write(prime+" "+(pos+1)+"\n");
                prime = primesReader.readLine();
                j+=prime.length();
                pos+=prime.length();
                if (j>=chunkSize) {
                    j-=chunkSize;
                    i++;
                }
            } else {
                pos++;
                j++;
                if (j==chunkSize) {
                    j=0;
                    i++;
                }
            }
        }
        primesReader.close();
        result.close();
    }

    private static boolean isCurrentPrime(char[][] pi, String prime, int i, int j) {
        boolean result = true;
        int i1 = i, j1 = j;
        for (int k=0; k<prime.length(); k++) {
            if (prime.charAt(k) == pi[i1][j1]) {
                j1++;
                if (j1 == pi[i1].length) {
                    j1 = 0;
                    i1++;
                }
                if (i1 == pi.length) {
                    result = false;
                    break;
                }
            } else {
                result = false;
                break;
            }
        }
        return result;
    }
}
The program expects to have pi.txt and primes.txt files in the same folder. It ignores first 2 symbols in pi.txt file to start from fraction part(assuming the file starts with 3. ). primes.txt is a list of primes(one line - one prime).
piSize variable should set to count of pi digits which we want to process.
newalex is offline   Reply With Quote