carmichael_from_multiple_recursive_mpz.pl 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 17 March 2023
  4. # https://github.com/trizen
  5. # Generate Carmichael numbers from a given multiple.
  6. # See also:
  7. # https://trizenx.blogspot.com/2020/08/pseudoprimes-construction-methods-and.html
  8. use 5.036;
  9. use Math::GMPz;
  10. use ntheory qw(:all);
  11. sub carmichael_from_multiple ($m, $callback, $reps = 1e3) {
  12. my $t = Math::GMPz::Rmpz_init();
  13. my $u = Math::GMPz::Rmpz_init();
  14. my $v = Math::GMPz::Rmpz_init();
  15. is_square_free($m) || return;
  16. my $L = lcm(map { subint($_, 1) } factor($m));
  17. $m = Math::GMPz->new("$m");
  18. $L = Math::GMPz->new("$L");
  19. Math::GMPz::Rmpz_invert($v, $m, $L) || return;
  20. for (my $p = Math::GMPz::Rmpz_init_set($v) ; --$reps >= 0 ; Math::GMPz::Rmpz_add($p, $p, $L)) {
  21. Math::GMPz::Rmpz_gcd($t, $m, $p);
  22. Math::GMPz::Rmpz_cmp_ui($t, 1) == 0 or next;
  23. my @factors = factor_exp($p);
  24. (vecall { $_->[1] == 1 } @factors) || next;
  25. Math::GMPz::Rmpz_mul($v, $m, $p);
  26. Math::GMPz::Rmpz_sub_ui($u, $v, 1);
  27. Math::GMPz::Rmpz_set_str($t, lcm(map { subint($_->[0], 1) } @factors), 10);
  28. if (Math::GMPz::Rmpz_divisible_p($u, $t)) {
  29. $callback->(Math::GMPz::Rmpz_init_set($v));
  30. }
  31. }
  32. }
  33. foreach my $p (@{primes(3, 100)}) {
  34. say "# Sieving with p = $p";
  35. my @list = ($p);
  36. while (@list) {
  37. my $m = shift(@list);
  38. carmichael_from_multiple(
  39. $m,
  40. sub ($n) {
  41. if ($n > $m) {
  42. if ($n > ~0) {
  43. say $n;
  44. }
  45. push @list, $n;
  46. }
  47. }
  48. );
  49. }
  50. }