#is there a faster algorithm to find nth prime?

7 messages · Page 1 of 1 (latest)

winter sundial
#

and if so can you explain just the concept or theory of it? I'm having lots of fun implementing the code and want to write it myself.

    static void makeComposite(int[] primeBools, int x) {
        primeBools[x/64] |= (1 << ((x >> 1) & 31));
    }
    public static int isComposite(int[] primeBools, int x) {
        return (primeBools[x/64] & (1 << ((x >> 1) & 31)));
    }
    public static long primeSieve(int n) {
        int estimatedLimit = (int)((Math.log(n) + Math.log(Math.log(n)) - 1 + ( (Math.log(Math.log(n)) - 2) / Math.log(n) )
                - (( Math.pow(Math.log(Math.log(n)),2) - 6 * Math.log(Math.log(n)) - 11 )/( 2 * Math.pow(Math.log(n),2) ))) * n);
        int[] isPrimeBools = new int[estimatedLimit/64 + 1];
        Arrays.fill(isPrimeBools, 0000);
        for (int i = 3; i * i <= estimatedLimit; i+=2) {
            if (isComposite(isPrimeBools, i) == 0) {
                for (int j = i*i, k = i << 1; j < estimatedLimit; j += k) {
                    makeComposite(isPrimeBools, j);
                }
            }
        }
        int finalPrime = 1;
        for (int foundPrimes = 1; foundPrimes <= n; finalPrime += 2) {
            if (isComposite(isPrimeBools, finalPrime) == 0) {
                foundPrimes++;
            }
        }
        return n == 1 ? 2 : finalPrime-2;
    }
weary grailBOT
#

This post has been reserved for your question.

Hey @winter sundial! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

winter sundial
#

i know i can make it multi-threaded, but that feels more like brute force than a clever solution

olive geyser
#

the prime sieve doesn't find the n-th prime, it finds the highest prime <= n

#

and there are also a few algorithm that give you "probable prime" numbers which are numbers that may be prime and don't have many prime factors (especially not low prime factors).
These probable primes are often used in cryptography