Which is the fastest algorithm to find prime numbers?

后端 未结 14 1428
情深已故
情深已故 2020-11-22 06:49

Which is the fastest algorithm to find out prime numbers using C++? I have used sieve\'s algorithm but I still want it to be faster!

14条回答
  •  醉话见心
    2020-11-22 07:03

    Is your problem to decide whether a particular number is prime? Then you need a primality test (easy). Or do you need all primes up to a given number? In that case prime sieves are good (easy, but require memory). Or do you need the prime factors of a number? This would require factorization (difficult for large numbers if you really want the most efficient methods). How large are the numbers you are looking at? 16 bits? 32 bits? bigger?

    One clever and efficient way is to pre-compute tables of primes and keep them in a file using a bit-level encoding. The file is considered one long bit vector whereas bit n represents integer n. If n is prime, its bit is set to one and to zero otherwise. Lookup is very fast (you compute the byte offset and a bit mask) and does not require loading the file in memory.

提交回复
热议问题