Which is the fastest algorithm to find prime numbers?

后端 未结 14 1427
情深已故
情深已故 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 06:53

    I know it's somewhat later, but this could be useful to people arriving here from searches. Anyway, here's some JavaScript that relies on the fact that only prime factors need to be tested, so the earlier primes generated by the code are re-used as test factors for later ones. Of course, all even and mod 5 values are filtered out first. The result will be in the array P, and this code can crunch 10 million primes in under 1.5 seconds on an i7 PC (or 100 million in about 20). Rewritten in C it should be very fast.

    var P = [1, 2], j, k, l = 3
    
    for (k = 3 ; k < 10000000 ; k += 2)
    {
      loop: if (++l < 5)
      {
        for (j = 2 ; P[j] <= Math.sqrt(k) ; ++j)
          if (k % P[j] == 0) break loop
    
        P[P.length] = k
      }
      else l = 0
    }
    

提交回复
热议问题