简体   繁体   中英

Find next prime number algorithm

I am looking forward to improve my algorithm to find the next primenumber to the right to a given number. What I have so far is this:

int NextPrime(int a)
{
    int i, j, count, num;
    for (i = a + 1; 1; i++)
    {
        for (j = 2, count = 0; j <= i; j++)
        {
            if (i%j == 0)
            {
                count++;
            }
        }
        if (count == 1)
        {
            return i;
            break;
        }
    }
}

Tho this algorithm is not that efficent when running often. Can someone give advices on how the algorithm could be speed up or improved.

Sieve of Eratosthenes is not the best solution when only one prime number should be found. Here is the solution which is useful for that purpose. It is based on the idea that all prime numbers are in form of 6k+-1, so I'm only testing 2, 3 and numbers in form 6+-1. Of course, the loop quits when divisor breaches sqrt(a) because all such numbers have already been tested.

bool IsPrime(int number)
{

    if (number == 2 || number == 3)
        return true;

    if (number % 2 == 0 || number % 3 == 0)
        return false;

    int divisor = 6;
    while (divisor * divisor - 2 * divisor + 1 <= number)
    {

        if (number % (divisor - 1) == 0)
            return false;

        if (number % (divisor + 1) == 0)
            return false;

        divisor += 6;

    }

    return true;

}

int NextPrime(int a)
{

    while (!IsPrime(++a)) 
    { }
    return a;

}

Net result is that this loop works very fast on a couple of large numbers I've tried.

You can improve upon the sieve of Eratosthenes by a lot if you only check each number against each prime before it up until the square root of the prime number. For this you need to keep a list of all primes up to then. This increases memory cost but increases execution speed by a long shot.

Pseudocode:

List foundPrimes;
foundPrimes.add(1)
foundPrimes.add(2)

bool isPrime(int x) {
    for (int divisor in foundPrimes) {
        if (divisor*divisor > x) {
            foundPrimes.add(x);
            return true;
        } else if (x % divisor==0) {
            return false;
        }
    }
    // Invalid, need to run the algo from 3 on to fill the list
}

int nextPrime(int x) {
    while (!isPrime(++x)) {}
    return x;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM