简体   繁体   中英

What is fastest way to find a prime number in range?

I have this code to find prime numbers:

void writePrimesToFile(int begin, int end, ofstream& file)
{
bool isPrime = 0;
for (int i = begin; i < end; i = i+2)
{
    isPrime = 1;
    for (int j = 2; j<i; j++)
        if (i % j == 0)
        {
            isPrime = 0;
            break;
        }
    if (isPrime)
        file << i << " \n";
}
}

Is there a faster way to do it? I tried googling a faster way but its all math and I don't understand how can I turn it into code.

Is there a faster way to do it?

Yes. There are faster primality test algorithms.

What is fastest way to find a prime number in range?

No one knows. If some one knows, then that person is guarding a massively important secret. No one has been able to prove that any of the known techniques is the fastest possible way to test primality.


You might have asked: What is the fastest known way to find a prime number in range.

The answer to that would be: It depends. The complexity of some algorithms grow asymptotically slower than that of other algorithms, but that is irrelevant if the input numbers are small. There are probabilistic methods that are very fast for some numbers, but have problematic cases where they are slower than deterministic methods.

Your input numbers are small, because they are of type int and therefore have quite limited range. With small numbers, a simple algorithm may be faster than a more complex one. To find out which algorithm is fastest for your use case, you must benchmark them.

I recommend starting with Sieve of Eratosthenes since it is asymptotically faster than your naïve approach, but also easy to implement (pseudo code courtesy of wikipedia):

Input: an integer n > 1

 Let A be an array of Boolean values, indexed by integers 2 to n,
 initially all set to true.

 for i = 2, 3, 4, ..., not exceeding √n:
   if A[i] is true:
     for j = i², i²+i, i²+2i, i²+3i, ..., not exceeding n :
       A[j] := false

 Output: all i such that A[i] is true.

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