PSW_primality_test.pl 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #!/usr/bin/perl
  2. # The PSW primality test, named after Carl Pomerance, John Selfridge, and Samuel Wagstaff.
  3. # No counter-examples are known to this test.
  4. # Algorithm: given an odd integer n, that is not a perfect power:
  5. # 1. Perform a (strong) base-2 Fermat test.
  6. # 2. Find the first P>0 such that kronecker(P^2 + 4, n) = -1.
  7. # 3. If the Lucas U sequence: U(P, -1, n+1) = 0 (mod n), then n is probably prime.
  8. # See also:
  9. # https://en.wikipedia.org/wiki/Lucas_pseudoprime
  10. # https://en.wikipedia.org/wiki/Baillie%E2%80%93PSW_primality_test
  11. use 5.020;
  12. use warnings;
  13. use experimental qw(signatures);
  14. use ntheory qw(is_prime is_power lucas_sequence kronecker powmod);
  15. sub findP($n) {
  16. # Find P such that kronecker(P^2 + 4, n) = -1.
  17. for (my $k = 1 ; ; ++$k) {
  18. if (kronecker($k*$k + 4, $n) == -1) {
  19. return $k;
  20. }
  21. }
  22. }
  23. sub PSW_primality_test ($n) {
  24. return 0 if $n <= 1;
  25. return 1 if $n == 2;
  26. return 0 if !($n & 1);
  27. return 0 if is_power($n);
  28. # Fermat base-2 test
  29. powmod(2, $n - 1, $n) == 1 or return 0;
  30. my $P = findP($n);
  31. my $Q = -1;
  32. # If LucasU(P, -1, n+1) = 0 (mod n), then n is probably prime.
  33. (lucas_sequence($n, $P, $Q, $n + 1))[0] == 0;
  34. }
  35. #
  36. ## Run some tests
  37. #
  38. my $from = 1;
  39. my $to = 1e6;
  40. my $count = 0;
  41. foreach my $n ($from .. $to) {
  42. if (PSW_primality_test($n)) {
  43. if (not is_prime($n)) {
  44. say "Counter-example: $n";
  45. }
  46. ++$count;
  47. }
  48. elsif (is_prime($n)) {
  49. say "Missed a prime: $n";
  50. }
  51. }
  52. say "There are $count primes between $from and $to.";