partial_sums_of_euler_totient_function_times_k_to_the_m.pl 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 07 February 2019
  4. # https://github.com/trizen
  5. # A sublinear algorithm for computing the partial sums of the Euler totient function times k^m.
  6. # The partial sums of the Euler totient function is defined as:
  7. #
  8. # a(n,m) = Sum_{k=1..n} k^m * phi(k)
  9. #
  10. # where phi(k) is the Euler totient function.
  11. # Example:
  12. # a(10^1, 1) = 217
  13. # a(10^2, 1) = 203085
  14. # a(10^3, 1) = 202870719
  15. # a(10^4, 1) = 202653667159
  16. # a(10^5, 1) = 202643891472849
  17. # a(10^6, 1) = 202642368741515819
  18. # a(10^7, 1) = 202642380629476099463
  19. # a(10^8, 1) = 202642367994273571457613
  20. # a(10^9, 1) = 202642367530671221417109931
  21. # General asymptotic formula:
  22. #
  23. # Sum_{k=1..n} k^m * phi(k) ~ F_(m+1)(n) / zeta(2).
  24. #
  25. # where F_m(n) are the Faulhaber polynomials.
  26. # OEIS sequences:
  27. # https://oeis.org/A011755 -- Sum_{k=1..n} k*phi(k).
  28. # https://oeis.org/A002088 -- Sum of totient function: a(n) = Sum_{k=1..n} phi(k).
  29. # https://oeis.org/A064018 -- Sum of the Euler totients phi for 10^n.
  30. # https://oeis.org/A272718 -- Partial sums of gcd-sum sequence A018804.
  31. # See also:
  32. # https://en.wikipedia.org/wiki/Faulhaber's_formula
  33. # https://en.wikipedia.org/wiki/Dirichlet_hyperbola_method
  34. # https://trizenx.blogspot.com/2018/11/partial-sums-of-arithmetical-functions.html
  35. use 5.020;
  36. use strict;
  37. use warnings;
  38. use experimental qw(signatures);
  39. use Math::AnyNum qw(faulhaber_sum ipow);
  40. use ntheory qw(euler_phi sqrtint rootint);
  41. sub partial_sums_of_euler_totient ($n, $m) {
  42. my $s = sqrtint($n);
  43. my @euler_sum_lookup = (0);
  44. my $lookup_size = 2 * rootint($n, 3)**2;
  45. my @euler_phi = euler_phi(0, $lookup_size);
  46. foreach my $i (1 .. $lookup_size) {
  47. $euler_sum_lookup[$i] = $euler_sum_lookup[$i - 1] + ipow($i, $m) * $euler_phi[$i];
  48. }
  49. my %seen;
  50. sub ($n) {
  51. if ($n <= $lookup_size) {
  52. return $euler_sum_lookup[$n];
  53. }
  54. if (exists $seen{$n}) {
  55. return $seen{$n};
  56. }
  57. my $s = sqrtint($n);
  58. my $T = faulhaber_sum($n, $m + 1);
  59. foreach my $k (2 .. int($n / ($s + 1))) {
  60. $T -= ipow($k, $m) * __SUB__->(int($n / $k));
  61. }
  62. foreach my $k (1 .. $s) {
  63. $T -= (faulhaber_sum(int($n / $k), $m) - faulhaber_sum(int($n / ($k + 1)), $m)) * __SUB__->($k);
  64. }
  65. $seen{$n} = $T;
  66. }->($n);
  67. }
  68. foreach my $n (1 .. 7) { # takes ~2.8 seconds
  69. say "a(10^$n, 1) = ", partial_sums_of_euler_totient(10**$n, 1);
  70. }