BPSW_primality_test.pl 1.7 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(forprimes foroddcomposites 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 BPSW_primality_test ($n) {
  14. return 0 if ($n <= 1);
  15. return 1 if ($n == 2);
  16. return 0 if is_power($n);
  17. powmod(2, $n - 1, $n) == 1 or return 0;
  18. my ($P, $Q) = (1, 0);
  19. for (my $k = 2 ; ; ++$k) {
  20. my $D = (-1)**$k * (2 * $k + 1);
  21. if (kronecker($D, $n) == -1) {
  22. $Q = (1 - $D) / 4;
  23. last;
  24. }
  25. }
  26. my $d = $n + 1;
  27. my $s = valuation($d, 2);
  28. $d >>= $s;
  29. my ($U) = lucas_sequence($n, $P, $Q, $d);
  30. return 1 if $U eq '0';
  31. foreach my $r (0 .. $s - 1) {
  32. my (undef, $V) = lucas_sequence($n, $P, $Q, $d << ($s - $r - 1));
  33. return 1 if $V eq '0';
  34. }
  35. return 0;
  36. }
  37. say "Sanity check...";
  38. forprimes {
  39. if (!BPSW_primality_test($_)) {
  40. die "Missed prime: $_";
  41. }
  42. } 1e6;
  43. foroddcomposites {
  44. if (BPSW_primality_test($_)) {
  45. die "Counter-example: $_";
  46. }
  47. } 1e6;
  48. say "Done...";
  49. say "Beginning the test...";
  50. my %seen;
  51. while (<>) {
  52. next if /^\h*#/;
  53. /\S/ or next;
  54. my $n = (split(' ', $_))[-1];
  55. $n || next;
  56. $n = Math::GMPz->new("$n");
  57. if (BPSW_primality_test($n)) {
  58. say "Counter-example: $n";
  59. }
  60. #ntheory::is_prime($n) && die "error: $n\n";
  61. #ntheory::is_prime($n) && die "error: $n\n";
  62. #ntheory::is_aks_prime($n) && die "error: $n\n";
  63. #ntheory::miller_rabin_random($n, 7) && die "error: $n\n";
  64. }