407 Idempotents -- v2.pl 677 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 25 August 2016
  4. # https://github.com/trizen
  5. # https://projecteuler.net/problem=407
  6. # Runtime: ~2 minutes
  7. use 5.010;
  8. use strict;
  9. use integer;
  10. use ntheory qw(:all);
  11. use List::Util qw(uniq product);
  12. my $limit = 10**7;
  13. my $sum = prime_count($limit);
  14. forcomposites {
  15. if (is_prime_power($_)) {
  16. ++$sum;
  17. }
  18. else {
  19. my $max = 0;
  20. my $rad = product(uniq(factor($_)));
  21. foreach my $d (divisors($rad)) {
  22. my $f = $_ / $d;
  23. my $g = $d * powmod($d, euler_phi($f) - 1, $f);
  24. $max = $g if ($g > $max);
  25. }
  26. $sum += $max;
  27. }
  28. } $limit;
  29. say $sum;