How can I test for primality?

前端 未结 16 2169
南方客
南方客 2020-12-05 08:29

I am writing a little library with some prime number related methods. As I\'ve done the groundwork (aka working methods) and now I\'m looking for some optimization. Ofcours

16条回答
  •  一整个雨季
    2020-12-05 09:05

    You might want to look into Fermat's little theorem.

    Here is the pseudo code from the book Algorithms by S. Dasgupta, C.H. Papadimitriou, and U.V. Vazirani, where n is the number you are testing for primality.

    Pick a positive integer a < n at random
    if a^n-1 is equivalent to 1 (mod n)
       return yes
    else
       return no
    

    Implementing Fermat's theorem should be faster then the sieve solution. However, there are Carmichael numbers that pass Fermat's test and are NOT prime. There are workarounds for this. I recommend consulting Section 1.3 in the fore mentioned book. It is all about primality testing and might be helpful for you.

提交回复
热议问题