patternMinor
What is the fastest to find just smallest prime number to a given number N where N can be as large as 10^18?
Viewed 0 times
smallestcanthenumberwhatjustwherelargefastestfind
Problem
During a programming contest I was asked to find just smallest prime number to given number N.
As Sieve cannot be used and brute force also doesn't work.
So, I was wondering is there any other faster implementation.
Here N -> (2, 10^18).
As Sieve cannot be used and brute force also doesn't work.
So, I was wondering is there any other faster implementation.
Here N -> (2, 10^18).
Solution
By fast primary testing you can test whether a given number is probably prime or not, actually methods like Miller Rabin are very fast and because we know the gap of size $O(\log n)$, between two consecutive primes, you can expect that when you start from $N$, you should visit few numbers by fast primarily testing, also, in most cases, fast primarily testing algorithms for the range you mentioned are correct.
In your case, because your numbers are bounded just few composite numbers can pass the miller rabin test which are:
2047, 1373653, 25326001, 3215031751, 2152302898747, 3474749660383, 341550071728321, 341550071728321
You can see them in this list, So you just need to check the number that passed the Miller Rabin test, is in above list or not, and by using this code, is possible to do it in less than a second.
In your case, because your numbers are bounded just few composite numbers can pass the miller rabin test which are:
2047, 1373653, 25326001, 3215031751, 2152302898747, 3474749660383, 341550071728321, 341550071728321
You can see them in this list, So you just need to check the number that passed the Miller Rabin test, is in above list or not, and by using this code, is possible to do it in less than a second.
Context
StackExchange Computer Science Q#11883, answer score: 4
Revisions (0)
No revisions yet.