unitary_divisors.pl 829 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 01 July 2018
  4. # https://github.com/trizen
  5. # A simple algorithm for generating the unitary divisors of a given number.
  6. # See also:
  7. # https://en.wikipedia.org/wiki/Unitary_divisor
  8. use 5.010;
  9. use strict;
  10. use warnings;
  11. use ntheory qw(forcomb factor_exp vecprod powint);
  12. # This algorithm nicely illustrates the identity:
  13. #
  14. # 2^n = Sum_{k=0..n} binomial(n, k)
  15. #
  16. # which is the number of divisors of a squarefree number that is the product of `n` primes.
  17. sub udivisors {
  18. my ($n) = @_;
  19. my @pp = map { powint($_->[0], $_->[1]) } factor_exp($n);
  20. my $len = scalar(@pp);
  21. my @d;
  22. foreach my $k (0 .. $len) {
  23. forcomb {
  24. push @d, vecprod(@pp[@_]);
  25. } $len, $k;
  26. }
  27. return sort { $a <=> $b } @d;
  28. }
  29. say join(' ', udivisors(5040));