sigma_function.pl 542 B

123456789101112131415161718192021222324252627282930
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 18 August 2017
  4. # https://github.com/trizen
  5. # Efficient implementation of the `sigma_k(n)` function, where k > 0.
  6. use 5.010;
  7. use strict;
  8. use warnings;
  9. use ntheory qw(factor_exp);
  10. sub sigma {
  11. my ($n, $k) = @_;
  12. my $sigma = 1;
  13. foreach my $p (factor_exp($n)) {
  14. $sigma *= (($p->[0]**($k * ($p->[1] + 1)) - 1) / ($p->[0]**$k - 1));
  15. }
  16. return $sigma;
  17. }
  18. say sigma(10, 1); #=> 18
  19. say sigma(100, 1); #=> 217
  20. say sigma(3628800, 2); #=> 20993420690550