How can I find the least prime number greater than a given number? For example, given 4, I need 5; given 7, I need 11.
I would like to know some ideas on best algorithms to do this. One method that I thought of was generate primes numbers through the Sieve of Eratosthenes, and then find the prime after the given number.
Source: Wikipedia
Bertrand's postulate (actually a theorem) states that if n > 3 is an integer, then there always exists at least one prime number p with n < p < 2n − 2. A weaker but more elegant formulation is: for every n > 1 there is always at least one prime p such that n < p < 2n.
So if I am given a number, say n, than I can check in the range (n, 2*n) [open interval excluding n and 2*n]
int GetNextPrime(int n)
{
bool isPrime = false;
for (int i = n; i < 2 * n; ++i)
{
// go with your regular prime checking routine
// as soon as you find a prime, break this for loop
}
}