partial_sums_of_gcd-sum_function_fast.sf 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/bin/ruby
  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 gcd-sum function, using Dirichlet's hyperbola method.
  6. # The partial sums of the gcd-sum function is defined as:
  7. #
  8. # a(n) = Sum_{k=1..n} Sum_{d|k} d*phi(k/d)
  9. #
  10. # where phi(k) is the Euler totient function.
  11. # Also equivalent with:
  12. # a(n) = Sum_{j=1..n} Sum_{i=1..j} gcd(i, j)
  13. # Based on the formula:
  14. # a(n) = (1/2)*Sum_{k=1..n} phi(k) * floor(n/k) * floor(1+n/k)
  15. # Example:
  16. # a(10^1) = 122
  17. # a(10^2) = 18065
  18. # a(10^3) = 2475190
  19. # a(10^4) = 317257140
  20. # a(10^5) = 38717197452
  21. # a(10^6) = 4571629173912
  22. # a(10^7) = 527148712519016
  23. # a(10^8) = 59713873168012716
  24. # a(10^9) = 6671288261316915052
  25. # OEIS sequences:
  26. # https://oeis.org/A272718 -- Partial sums of gcd-sum sequence A018804.
  27. # https://oeis.org/A018804 -- Pillai's arithmetical function: Sum_{k=1..n} gcd(k, n).
  28. # See also:
  29. # https://en.wikipedia.org/wiki/Dirichlet_hyperbola_method
  30. # https://trizenx.blogspot.com/2018/11/partial-sums-of-arithmetical-functions.html
  31. func partial_sums_of_gcd_sum_function(n) {
  32. var s = n.isqrt
  33. var euler_sum_lookup = [0]
  34. var lookup_size = (2 + 2*n.iroot(3)**2)
  35. var euler_phi_lookup = [0]
  36. for k in (1 .. lookup_size) {
  37. euler_sum_lookup[k] = (euler_sum_lookup[k-1] + (euler_phi_lookup[k] = k.euler_phi))
  38. }
  39. var seen = Hash()
  40. func euler_phi_partial_sum(n) {
  41. if (n <= lookup_size) {
  42. return euler_sum_lookup[n]
  43. }
  44. if (seen.has(n)) {
  45. return seen{n}
  46. }
  47. var s = n.isqrt
  48. var T = n.faulhaber(1)
  49. var A = sum(2..s, {|k|
  50. __FUNC__(floor(n/k))
  51. })
  52. var B = sum(1 .. floor(n/s)-1, {|k|
  53. (floor(n/k) - floor(n/(k+1))) * __FUNC__(k)
  54. })
  55. seen{n} = (T - A - B)
  56. }
  57. var A = sum(1..s, {|k|
  58. var t = floor(n/k)
  59. (k * euler_phi_partial_sum(t)) + (euler_phi_lookup[k] * t.faulhaber(1))
  60. })
  61. var T = s.faulhaber(1)
  62. var C = euler_phi_partial_sum(s)
  63. return (A - T*C)
  64. }
  65. say 20.of { partial_sums_of_gcd_sum_function(_) }
  66. __END__
  67. [0, 1, 4, 9, 17, 26, 41, 54, 74, 95, 122, 143, 183, 208, 247, 292, 340, 373, 436, 473]