carmichael_numbers_generation_erdos_method_dynamic_programming.pl 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #!/usr/bin/perl
  2. # Erdos construction method for Carmichael numbers:
  3. # 1. Choose an even integer L with many prime factors.
  4. # 2. Let P be the set of primes d+1, where d|L and d+1 does not divide L.
  5. # 3. Find a subset S of P such that prod(S) == 1 (mod L). Then prod(S) is a Carmichael number.
  6. # Alternatively:
  7. # 3. Find a subset S of P such that prod(S) == prod(P) (mod L). Then prod(P) / prod(S) is a Carmichael number.
  8. use 5.036;
  9. use Math::GMPz qw();
  10. use ntheory qw(:all);
  11. # Primes p such that p-1 divides L and p does not divide L
  12. sub lambda_primes ($L) {
  13. grep { $_ > 2 and $L % $_ != 0 and is_prime($_) } map { $_ + 1 } divisors($L);
  14. }
  15. sub method_1 ($L, $callback) { # smallest numbers first
  16. my @P = lambda_primes($L);
  17. my @d = (Math::GMPz->new(1));
  18. foreach my $p (@P) {
  19. my @t;
  20. foreach my $u (@d) {
  21. my $t = $u * $p;
  22. push(@t, $t);
  23. if ($t % $L == 1) {
  24. $callback->($t);
  25. }
  26. }
  27. push @d, @t;
  28. }
  29. return;
  30. }
  31. sub method_2 ($L, $callback) { # largest numbers first
  32. my @P = lambda_primes($L);
  33. my @d = (Math::GMPz->new(1));
  34. my $T = Math::GMPz->new(vecprod(@P));
  35. my $s = $T % $L;
  36. foreach my $p (@P) {
  37. my @t;
  38. foreach my $u (@d) {
  39. my $t = $u * $p;
  40. push(@t, $t);
  41. if ($t % $L == $s) {
  42. $callback->($T / $t) if ($T != $t);
  43. }
  44. }
  45. push @d, @t;
  46. }
  47. return;
  48. }
  49. method_1(720, sub ($c) { say $c });
  50. method_2(720, sub ($c) { say $c });
  51. __END__
  52. 41041
  53. 172081
  54. 15841
  55. 16778881
  56. 832060801
  57. 5310721
  58. 76595761
  59. 488881
  60. 20064165121
  61. 84127131361
  62. 561777121
  63. 18162001
  64. 115921
  65. 1932608161
  66. 133205761
  67. 1836304561
  68. 12262321
  69. 30614445878401
  70. 2110112460001
  71. 609865201
  72. 1945024664401
  73. 8879057210881
  74. 354725143201
  75. 3305455474321
  76. 1487328704641
  77. 65121765643441