partial_sums_of_euler_totient_function_fast.pl 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 04 February 2019
  4. # https://github.com/trizen
  5. # A sublinear algorithm for computing the partial sums of the Euler totient function.
  6. # The partial sums of the Euler totient function is defined as:
  7. #
  8. # a(n) = Sum_{k=1..n} phi(k)
  9. #
  10. # where phi(k) is the Euler totient function.
  11. # Recursive formula:
  12. # a(n) = n*(n+1)/2 - Sum_{k=2..sqrt(n)} a(floor(n/k)) - Sum_{k=1..floor(n/sqrt(n))-1} a(k) * (floor(n/k) - floor(n/(k+1)))
  13. # Example:
  14. # a(10^1) = 32
  15. # a(10^2) = 3044
  16. # a(10^3) = 304192
  17. # a(10^4) = 30397486
  18. # a(10^5) = 3039650754
  19. # a(10^6) = 303963552392
  20. # a(10^7) = 30396356427242
  21. # a(10^8) = 3039635516365908
  22. # a(10^9) = 303963551173008414
  23. # OEIS sequences:
  24. # https://oeis.org/A002088 -- Sum of totient function: a(n) = Sum_{k=1..n} phi(k).
  25. # https://oeis.org/A064018 -- Sum of the Euler totients phi for 10^n.
  26. # https://oeis.org/A272718 -- Partial sums of gcd-sum sequence A018804.
  27. # See also:
  28. # https://en.wikipedia.org/wiki/Dirichlet_hyperbola_method
  29. # https://trizenx.blogspot.com/2018/11/partial-sums-of-arithmetical-functions.html
  30. use 5.020;
  31. use strict;
  32. use warnings;
  33. use experimental qw(signatures);
  34. use ntheory qw(euler_phi sqrtint rootint);
  35. sub partial_sums_of_euler_totient($n) {
  36. my $s = sqrtint($n);
  37. my @euler_sum_lookup = (0);
  38. my $lookup_size = 2 * rootint($n, 3)**2;
  39. my @euler_phi = euler_phi(0, $lookup_size);
  40. foreach my $i (1 .. $lookup_size) {
  41. $euler_sum_lookup[$i] = $euler_sum_lookup[$i - 1] + $euler_phi[$i];
  42. }
  43. my %seen;
  44. sub ($n) {
  45. if ($n <= $lookup_size) {
  46. return $euler_sum_lookup[$n];
  47. }
  48. if (exists $seen{$n}) {
  49. return $seen{$n};
  50. }
  51. my $s = sqrtint($n);
  52. my $T = ($n * ($n + 1)) >> 1;
  53. foreach my $k (2 .. int($n / ($s + 1))) {
  54. $T -= __SUB__->(int($n / $k));
  55. }
  56. foreach my $k (1 .. $s) {
  57. $T -= (int($n / $k) - int($n / ($k + 1))) * __SUB__->($k);
  58. }
  59. $seen{$n} = $T;
  60. }->($n);
  61. }
  62. foreach my $n (1 .. 8) { # takes less than 1 second
  63. say "a(10^$n) = ", partial_sums_of_euler_totient(10**$n);
  64. }