PSW_primality_test.pl 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/usr/bin/perl
  2. use 5.020;
  3. use strict;
  4. use warnings;
  5. use experimental qw(signatures);
  6. use Math::GMPz;
  7. use Math::AnyNum qw(fibmod lucasmod);
  8. use ntheory qw(foroddcomposites forprimes is_prime powmod kronecker is_power valuation);
  9. use Math::Prime::Util::GMP qw(lucas_sequence);
  10. use 5.020;
  11. use warnings;
  12. use experimental qw(signatures);
  13. sub PSW_primality_test ($n) {
  14. if (ref($n) ne 'Math::GMPz') {
  15. $n = Math::GMPz->new("$n");
  16. }
  17. return 0 if Math::GMPz::Rmpz_cmp_ui($n, 1) <= 0;
  18. return 1 if Math::GMPz::Rmpz_cmp_ui($n, 2) == 0;
  19. return 0 if Math::GMPz::Rmpz_even_p($n);
  20. return 0 if Math::GMPz::Rmpz_perfect_power_p($n);
  21. my $d = Math::GMPz::Rmpz_init();
  22. my $t = Math::GMPz::Rmpz_init_set_ui(2);
  23. # Fermat base-2 test
  24. Math::GMPz::Rmpz_sub_ui($d, $n, 1);
  25. Math::GMPz::Rmpz_powm($t, $t, $d, $n);
  26. Math::GMPz::Rmpz_cmp_ui($t, 1) and return 0;
  27. # In general, we find P such that kronecker(P^2 + 4, n) = -1.
  28. my $P;
  29. for (my $k = 1 ; ; ++$k) {
  30. if (Math::GMPz::Rmpz_ui_kronecker($k * $k + 4, $n) == -1) {
  31. $P = $k;
  32. last;
  33. }
  34. }
  35. # If LucasU(P, -1, n+1) = 0 (mod n), then n is probably prime.
  36. (lucas_sequence($n, $P, -1, $n + 1))[0] == 0;
  37. }
  38. say "Sanity check...";
  39. forprimes {
  40. if (!PSW_primality_test($_)) {
  41. die "Missed prime: $_";
  42. }
  43. }
  44. 1e6;
  45. foroddcomposites {
  46. if (PSW_primality_test($_)) {
  47. die "Counter-example: $_";
  48. }
  49. }
  50. 1e6;
  51. say "Done...";
  52. say "Beginning the test...";
  53. my %seen;
  54. while (<>) {
  55. next if /^\h*#/;
  56. /\S/ or next;
  57. my $n = (split(' ', $_))[-1];
  58. $n || next;
  59. $n = Math::GMPz->new("$n");
  60. if (PSW_primality_test($n)) {
  61. say "Counter-example: $n";
  62. }
  63. #ntheory::is_prime($n) && die "error: $n\n";
  64. #ntheory::is_prime($n) && die "error: $n\n";
  65. #ntheory::is_aks_prime($n) && die "error: $n\n";
  66. #ntheory::miller_rabin_random($n, 7) && die "error: $n\n";
  67. }