Find a largest prime number less than n [closed]

早过忘川 提交于 2019-12-29 08:25:11

问题


How can I find a largest prime number which is less than n, where n ≤ 10¹⁸ ? Please help me find an Efficient Algorithm.

for(j=n;j>=2;j--) {
  if(j%2 == 1) {
    double m = double(j);
    double a = (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 this approach but this is not efficient to solve for n>10^10;

How to optimize this..

Edit: Solution: Use Primality test on each j.

Miller Rabin, Fermat's Test.


回答1:


I don't think this question should be so quickly dismissed, as efficiency is not so easy to determine for numbers in this range. First of all, given the average prime gap is ln(p), it makes sense to work down from the given (n). i.e., ln(10^18) ~ 41.44), so you would expect around 41 iterations on average working down from (n). e.g., testing: (n), (n - 2), (n - 4), ...

Given this average gap, the next step is to decide whether you wish to use a naive test - check for divisibility by primes <= floor(sqrt(n)). With n <= (10^18), you would need to test against primes <= (10^9). There are ~ 50 million primes in this range. If you are willing to precompute and tabulate these values (all of which fit in 32 bits), you have a reasonable test for 64-bit values n <= 10^18. In this case, is a 200MB prime table an acceptable approach? 20 years ago, it might not have been. Today, it's not an issue.

Combining a prime table with sieving and/or Pocklington's test might improve efficiency. Alternatively, if memory is more constrained, a deterministic variant of the Miller-Rabin test with bases: 2, 325, 9375, 28178, 450775, 9780504, 1795265022 (SPRP set). Most composites fail immediately with an SPRP-2 test.

The point is - you have a decision to make between algorithmic complexity, both theoretical and in terms of implementation difficulty, and a balance with space/time trade-offs.



来源:https://stackoverflow.com/questions/16375681/find-a-largest-prime-number-less-than-n

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!