carmichael_numbers_from_multiple_mpz.pl 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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) {
  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) ; ; 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. carmichael_from_multiple(13 * 19, sub ($n) { say $n });