reporting all prime numbers less than n

前端 未结 2 1713
暖寄归人
暖寄归人 2021-01-16 20:06

I need to print all the prime numbers less than a given number n. I can use sieve of Eratothenes but the running time of that algorithm IS NOT O(n). Is there any O(n) time s

2条回答
  •  离开以前
    2021-01-16 20:19

    I don't think you'll find an algorithm for checking an arbitrary number for primality with an O(n) time complexity. I'm pretty certain the NSA (and any other organisations that deal with crypto issues) wouldn't be very happy with that :-)

    The only way you'll get an O(n) or better way is to pre-calculate (for example) the first fifty million primes (or use someone else's already-precalculated list) and use that as a lookup. I have such a file locally and it's a simple matter of running grep over it to see if the number is prime. It doesn't help for arbitrary numbers but I rarely have to use ones that big. Crypto guys, of course, would consider such a list vanishingly small for their purposes.

    And, if you turn it into a bitmap (about 120M for the first fifty million primes), you can even even reduce the complexity to O(1) by simply turning the number into a byte offset and bit mask - a couple of bit shifts and/or bitwise operations.

    However, getting a list of the primes below a certain n is certainly doable in O(n) time complexity. The Atkin and Bernstein paper detailing the Sieve of Atkin claims:

    We introduce an algorithm that computes the prime numbers up to N using O(N/log(log(N))) additions ...

    which is actually slightly better than O(n).

    However, it's still unlikely to compete with a lookup solution. My advice would be to use Atkin or Eratosthenes to make a list - it doesn't really matter since you'll only be doing this bit once so performance would not be critical.

    Then use the list itself for checking primality.

提交回复
热议问题