Which is the fastest algorithm to find prime numbers?

后端 未结 14 1426
情深已故
情深已故 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:01

    There is a 100% mathematical test that will check if a number P is prime or composite, called AKS Primality Test.

    The concept is simple: given a number P, if all the coefficients of (x-1)^P - (x^P-1) are divisible by P, then P is a prime number, otherwise it is a composite number.

    For instance, given P = 3, would give the polynomial:

       (x-1)^3 - (x^3 - 1)
     = x^3 + 3x^2 - 3x - 1 - (x^3 - 1)
     = 3x^2 - 3x
    

    And the coefficients are both divisible by 3, therefore the number is prime.

    And example where P = 4, which is NOT a prime would yield:

       (x-1)^4 - (x^4-1)
     = x^4 - 4x^3 + 6x^2 - 4x + 1 - (x^4 - 1)
     = -4x^3 + 6x^2 - 4x
    

    And here we can see that the coefficients 6 is not divisible by 4, therefore it is NOT prime.

    The polynomial (x-1)^P will P+1 terms and can be found using combination. So, this test will run in O(n) runtime, so I don't know how useful this would be since you can simply iterate over i from 0 to p and test for the remainder.

提交回复
热议问题