Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to find a prime number? [closed]

Tags:

c++

what will be the best way to find a prime number so that the time complexity is much reduced.

like image 705
d3vdpro Avatar asked Sep 15 '09 18:09

d3vdpro


6 Answers

When it comes to finding prime numbers, the Sieve of Eratosthenes and the Sieve of Atkin are two possible solutions. The Sieve of Eratosthenes has a complexity of O((n log n)(log log n)). The Sieve of Atkin has a complexity of O(N / log log n).

If you have a number and you want to find out if it's prime, that is called performing a primality test. The naive approach is to check all numbers m from 2 to sqrt(n) and verify that n % m is not 0. If you want to expand this slightly, you can throw out all even numbers (except 2). There are also some other enhancements to this naive approach that might improve performance, along with other, more advanced techniques.

like image 124
Thomas Owens Avatar answered Nov 11 '22 01:11

Thomas Owens


Use sieve of Eratosthenes is if you want to enumerate primes. If you want to generate a large prime, generate a random odd number and check for primality.

like image 39
avakar Avatar answered Nov 11 '22 02:11

avakar


If it's below a certain range, best way would be to look it up in a precomputed list. There's plenty of them, up to very high numbers.

Example, all the primes up to 10,000,000,000 at http://www.prime-numbers.org/

like image 40
JRL Avatar answered Nov 11 '22 02:11

JRL


Inspired by xkcd:

int findPrimeNumber() {
    return 2; // guaranteed to be prime
}
like image 44
JorenHeit Avatar answered Nov 11 '22 02:11

JorenHeit


If you want to generate primes from 1 to whatever, then the fastest way is probably a wheeled Sieve as implemented here, which can typically test more than 3,000,000 candidate primes a second on an average laptop (and that's using an unoptimized language like VB.net), and factor the non-primes to boot. In c++ it could be easily 5 to 20 times faster.

like image 3
RBarryYoung Avatar answered Nov 11 '22 01:11

RBarryYoung


Although there are more efficient algorithms, the Miller-Rabin primality test is one of the simplest tests to implement.

like image 1
Brian Avatar answered Nov 11 '22 00:11

Brian