algorithm - Find a largest prime number less than n -


how can find largest prime number less n, n ≤ 10¹⁸ ? please me find efficient algorithm.

for(j=n;j>=2;j--) {   if(j%2 == 1) {     double m = double(j);     double = (m-1)/6.0;     double b = (m-5)/6.0;     if( a-(int)a == 0 || b-(int)b == 0 ) {       printf("%llu\n",j);       break;     }   } } 

i used approach not efficient solve n>10^10;

how optimize this..

edit: solution: use primality test on each j.

miller rabin, fermat's test.

i don't think question should dismissed, efficiency not easy determine numbers in range. first of all, given average prime gap ln(p), makes sense work down given (n). i.e., ln(10^18) ~ 41.44), expect around 41 iterations on average working down (n). e.g., testing: (n), (n - 2), (n - 4), ...

given average gap, next step decide whether wish use naive test - check divisibility primes <= floor(sqrt(n)). n <= (10^18), need test against primes <= (10^9). there ~ 50 million primes in range. if willing precompute , tabulate these values (all of fit in 32 bits), have reasonable test 64-bit values n <= 10^18. in case, 200mb prime table acceptable approach? 20 years ago, might not have been. today, it's not issue.

combining prime table sieving and/or pocklington's test might improve efficiency. alternatively, if memory more constrained, deterministic variant of miller-rabin test bases: 2, 325, 9375, 28178, 450775, 9780504, 1795265022 (sprp set). composites fail sprp-2 test.

the point - have decision make between algorithmic complexity, both theoretical , in terms of implementation difficulty, , balance space/time trade-offs.


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -