yafu_factorization.pl 789 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/usr/bin/perl
  2. # Factorize a given number, using the `YAFU` tool, and parse the output into an array of `Math::GMPz` objects.
  3. # See also:
  4. # https://sourceforge.net/projects/yafu/
  5. use 5.020;
  6. use strict;
  7. use warnings;
  8. use Math::GMPz;
  9. use experimental qw(signatures);
  10. use File::Spec::Functions qw(rel2abs curdir tmpdir);
  11. sub yafu_factor ($n) {
  12. $n = Math::GMPz->new($n); # validate the number
  13. my $dir = rel2abs(curdir());
  14. chdir(tmpdir());
  15. my $output = qx(yafu 'factor($n)');
  16. chdir($dir);
  17. my @factors;
  18. while ($output =~ /^P\d+ = (\d+)/mg) {
  19. push @factors, Math::GMPz->new($1);
  20. }
  21. return sort { $a <=> $b } @factors;
  22. }
  23. my $n = shift() || die "usage: $0 [n]\n";
  24. my @factors = yafu_factor($n);
  25. say "$n = [", join(', ', @factors), ']';