745 Sum of Squares -- v2.pl 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 31 January 2021
  4. # https://github.com/trizen
  5. # Sum of Squares
  6. # https://projecteuler.net/problem=745
  7. # Formula:
  8. # S(n) = Sum_{k=1..floor(sqrt(n))} k^2 * R(floor(n/k^2))
  9. # Where R(n) is the number of squarefree numbers <= n:
  10. # R(n) = Sum_{k=1..floor(sqrt(n))} moebius(k) * floor(n/k^2)
  11. # Faster formula:
  12. # S(n) = Sum_{k=1..floor(sqrt(n))} J_2(k) * floor(n / k^2)
  13. # Where J_n(x) is the Jordan totient function.
  14. # S(10^1) = 24
  15. # S(10^2) = 767
  16. # S(10^3) = 22606
  17. # S(10^4) = 722592
  18. # S(10^5) = 22910120
  19. # S(10^6) = 725086120
  20. # S(10^7) = 22910324448
  21. # S(10^8) = 724475280152
  22. # S(10^9) = 22907428923832
  23. # S(10^10) = 724420596049320
  24. # S(10^11) = 22908061437420776
  25. # S(10^12) = 724418227020757048
  26. # S(10^13) = 22908104289912800016
  27. # Runtime: 8.530s
  28. use 5.020;
  29. use warnings;
  30. use ntheory qw(:all);
  31. use experimental qw(signatures);
  32. sub S ($n, $MOD) {
  33. my $total = 0;
  34. foreach my $k (1 .. sqrtint($n)) {
  35. $total += mulmod(divint($n, $k * $k), jordan_totient(2, $k), $MOD);
  36. }
  37. $total % $MOD;
  38. }
  39. say S(powint(10, 14), 1_000_000_007);