PSW_primality_test_mpz.pl 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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 Math::GMPz;
  15. use ntheory qw(is_prime lucas_sequence);
  16. sub PSW_primality_test ($n) {
  17. $n = Math::GMPz->new("$n");
  18. return 0 if Math::GMPz::Rmpz_cmp_ui($n, 1) <= 0;
  19. return 1 if Math::GMPz::Rmpz_cmp_ui($n, 2) == 0;
  20. return 0 if Math::GMPz::Rmpz_even_p($n);
  21. return 0 if Math::GMPz::Rmpz_perfect_power_p($n);
  22. my $d = Math::GMPz::Rmpz_init();
  23. my $t = Math::GMPz::Rmpz_init_set_ui(2);
  24. # Fermat base-2 test
  25. Math::GMPz::Rmpz_sub_ui($d, $n, 1);
  26. Math::GMPz::Rmpz_powm($t, $t, $d, $n);
  27. Math::GMPz::Rmpz_cmp_ui($t, 1) and return 0;
  28. # Find P such that kronecker(P^2 - 4*Q, n) = -1.
  29. my $P;
  30. for (my $k = 1 ; ; ++$k) {
  31. if (Math::GMPz::Rmpz_ui_kronecker($k * $k + 4, $n) == -1) {
  32. $P = $k;
  33. last;
  34. }
  35. }
  36. # If LucasU(P, -1, n+1) = 0 (mod n), then n is probably prime.
  37. (lucas_sequence($n, $P, -1, $n + 1))[0] == 0;
  38. }
  39. #
  40. ## Run some tests
  41. #
  42. my $from = 1;
  43. my $to = 1e5;
  44. my $count = 0;
  45. foreach my $n ($from .. $to) {
  46. if (PSW_primality_test($n)) {
  47. if (not is_prime($n)) {
  48. say "Counter-example: $n";
  49. }
  50. ++$count;
  51. }
  52. elsif (is_prime($n)) {
  53. say "Missed a prime: $n";
  54. }
  55. }
  56. say "There are $count primes between $from and $to.";