A well-known problem is, given a prime number P, find the next smallest prime number. An algorithm to solve this is to go to P+1, check if it's prime by checking the divisibility of all numbers from 2 up to floor(sqrt(P+1)) (Because all prime divisors of a number will be smaller or equal to it's square root), then check the same for P+2, P+3 and so on, until a prime number is found. Prove that the complexity of this algorithm is O(P).
Solution:
According to Andrica's conjecture , for two prime numbers p and q with p < q and no other prime between them (q is the next smallest prime after p), sqrt(q) — sqrt(p) < 1 which becomes q < p + 2\sqrt(p) + 1 and since they are natural numbers, q <= p + 2*sqrt(p). Therefore, the gap between p and q is at most 2*sqrt(p).
This means that our algorithm will check at most 2*sqrt(p) numbers (or to be more precise, floor(2*sqrt(p)) ). For each number we will check up to its square root, therefore we will do floor(sqrt(p+1)) + floor(sqrt(p+2)) + floor(sqrt(p+3)) + ... + floor(sqrt(p + 2*floor(sqrt(p)))) operations in total. But all the elements are < floor(sqrt(p + p)) = floor(sqrt(2*p)). There are floor(sqrt(2*p)) elements, so the total number of operations is less than floor(sqrt(2*p))*floor(sqrt(2\p)) <= 2*p. Thus this algorithm will do up to 2*P operations and the complexity will be O(P).
You can use faster than O(sqrt(p)) primality tests.
Indeed but the whole point was to prove that this algorithm is faster than you'd expect it to be and the complexity is very pretty.
Even if check is done in O(sqrt(p)) for each number it's still much faster then sqrt(p) * range especially if we know that there is no other primes.
Each 2nd check is done in 1 operation (divisibility by two), echo 3rd of others in 2 operation, etc
That's a cool observation. Ignoring the fact that the prime-gap is relatively small for small numbers, can we get some better complexity for this algorithm using your observation?
I tried to get prove a better one but with no success. I think it's obvious that O(P) is too much :P
A long time ago I set a problem about it. I couldn't find two consecutive prime numbers with at least 100 units gap. I bounded this value as ln(P) because I considered prime numbers to distribute in pretty uniform way. Are there any proofs or counter-examples for my assumptions?
Well, it's not that hard to find numbers with difference more than 100.
If I don't miss something the largest difference up to 10^9 is 282 between 436273009 and 436273291 (actually I tested it hen we set up another problem)
Heh, seems to be consistent with wikipedia
http://en.wikipedia.org/wiki/Prime_gap I think this will help you.
I like that:)
More logs for the king of logs! :)