dirichlet_hyperbola_method.sf 923 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #!/usr/bin/ruby
  2. # Simple implementation of Dirichlet's hyperbola method.
  3. # This is one of the most beautiful formulas in mathematics!
  4. # See also:
  5. # https://en.wikipedia.org/wiki/Dirichlet_hyperbola_method
  6. func dirichlet_hyperbola_method(n,
  7. g = { _ },
  8. h = { _ },
  9. G = {|n| sum(1..n, g) },
  10. H = {|n| sum(1..n, h) }
  11. ) {
  12. var s = n.isqrt
  13. var A = sum(1..s, {|a|
  14. g(a) * H(floor(n/a))
  15. })
  16. var B = sum(1..s, {|b|
  17. h(b) * G(floor(n/b))
  18. })
  19. A + B - (G(s) * H(s))
  20. }
  21. func test_sum(n, g, h) {
  22. sum(1..n, {|k|
  23. k.divisors.sum {|d|
  24. g(d) * h(k/d)
  25. }
  26. })
  27. }
  28. func g(n) { n }
  29. func h(n) { moebius(n) }
  30. say 20.of { test_sum(_, g, h) }
  31. say 20.of { dirichlet_hyperbola_method(_, g, h) }
  32. __END__
  33. [0, 1, 2, 4, 6, 10, 12, 18, 22, 28, 32, 42, 46, 58, 64, 72, 80, 96, 102, 120]
  34. [0, 1, 2, 4, 6, 10, 12, 18, 22, 28, 32, 42, 46, 58, 64, 72, 80, 96, 102, 120]