407 Idempotents -- v3.pl 872 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 30 August 2019
  4. # https://github.com/trizen
  5. # https://projecteuler.net/problem=407
  6. # Runtime: ~1 minute
  7. # See also:
  8. # https://oeis.org/A182665 -- Greatest x < n such that n divides x*(x-1).
  9. # M(n) = 1 iff n is a prime power p^k with k >= 1.
  10. # a^2 == a (mod n) iff
  11. #
  12. # a == 0 (mod x) and
  13. # a == 1 (mod y)
  14. #
  15. # where n = x*y and gcd(x,y) = 1.
  16. # From this, we see that:
  17. # a = x * invmod(x, y)
  18. use 5.010;
  19. use strict;
  20. use integer;
  21. use ntheory qw(:all);
  22. my $limit = 10**7;
  23. my $sum = prime_count($limit);
  24. forcomposites {
  25. if (is_prime_power($_)) {
  26. ++$sum;
  27. }
  28. else {
  29. my $max = 0;
  30. foreach my $d (divisors($_)) {
  31. my $f = $_/$d;
  32. my $g = $d * invmod($d, $f);
  33. $max = $g if ($g > $max);
  34. }
  35. $sum += $max;
  36. }
  37. } $limit;
  38. say $sum;