flt_factorization_method.pl 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #!/usr/bin/perl
  2. # Author: Daniel "Trizen" Șuteu
  3. # Date: 02 August 2020
  4. # Edit: 07 January 2021
  5. # https://github.com/trizen
  6. # A new factorization method for numbers that have all prime factors close to each other.
  7. # Inpsired by Fermat's Little Theorem (FLT).
  8. use 5.014;
  9. use warnings;
  10. use Math::GMPz;
  11. use ntheory qw(:all);
  12. use POSIX qw(ULONG_MAX);
  13. sub flt_factor {
  14. my ($n, $base, $reps) = @_;
  15. # base: a native integer <= sqrt(ULONG_MAX)
  16. # reps: how many tries before giving up
  17. if (ref($n) ne 'Math::GMPz') {
  18. $n = Math::GMPz->new("$n");
  19. }
  20. $base = 2 if (!defined($base) or $base < 2);
  21. $reps = 1e6 if (!defined($reps));
  22. my $z = Math::GMPz::Rmpz_init();
  23. my $t = Math::GMPz::Rmpz_init();
  24. my $g = Math::GMPz::Rmpz_init();
  25. Math::GMPz::Rmpz_set_ui($z, $base);
  26. Math::GMPz::Rmpz_set_ui($t, $base);
  27. Math::GMPz::Rmpz_powm($z, $z, $n, $n);
  28. # Cannot factor Fermat pseudoprimes
  29. if (Math::GMPz::Rmpz_cmp_ui($z, $base) == 0) {
  30. return ($n);
  31. }
  32. my $multiplier = $base * $base;
  33. if ($multiplier > ULONG_MAX) { # base is too large
  34. return ($n);
  35. }
  36. for (my $j = 1 ; $j <= $reps ; $j += 1) {
  37. Math::GMPz::Rmpz_mul_ui($t, $t, $multiplier);
  38. Math::GMPz::Rmpz_mod($t, $t, $n) if ($j % 10 == 0);
  39. Math::GMPz::Rmpz_sub($g, $z, $t);
  40. Math::GMPz::Rmpz_gcd($g, $g, $n);
  41. if (Math::GMPz::Rmpz_cmp_ui($g, 1) > 0) {
  42. if (Math::GMPz::Rmpz_cmp($g, $n) == 0) {
  43. return ($n);
  44. }
  45. my $x = Math::GMPz::Rmpz_init();
  46. my $y = Math::GMPz::Rmpz_init();
  47. Math::GMPz::Rmpz_set($y, $g);
  48. Math::GMPz::Rmpz_divexact($x, $n, $g);
  49. return sort { Math::GMPz::Rmpz_cmp($a, $b) } ($x, $y);
  50. }
  51. }
  52. return $n;
  53. }
  54. my $p = random_ndigit_prime(30);
  55. say join ' * ', flt_factor("173315617708997561998574166143524347111328490824959334367069087");
  56. say join ' * ', flt_factor("2425361208749736840354501506901183117777758034612345610725789878400467");
  57. say join ' * ', flt_factor(vecprod($p, next_prime($p), next_prime(next_prime($p))));
  58. say join ' * ', flt_factor(vecprod($p, next_prime(13 * $p), next_prime(123 * $p)));
  59. say join ' * ', flt_factor(vecprod($p, next_prime($p), next_prime(next_prime($p)), powint(2, 128) + 1));