harmonic_numbers_closed_form.sf 705 B

12345678910111213141516171819202122
  1. #!/usr/bin/ruby
  2. # A remarkable closed-form to the n-th Harmonic number:
  3. # H_n = ((binomial(n + (n+1)!, n) - 1) / (n+1)!) - (n+1)*floor(((binomial(n + (n+1)!, n) - 1) / (n+1)!) / (n+1))
  4. # Can it be computed efficiently?
  5. # See also:
  6. # https://en.wikipedia.org/wiki/Harmonic_number
  7. # https://math.stackexchange.com/questions/52572/do-harmonic-numbers-have-a-closed-form-expression
  8. # Formula posted by nczksv on math.stackexchange.com (5th April 2018):
  9. # https://math.stackexchange.com/a/2723193
  10. func H(n) {
  11. with ((binomial(n + (n+1)!, n) - 1) / (n+1)!) {|g|
  12. g - (n+1)*floor(g / (n+1))
  13. }
  14. }
  15. say 10.of(H) #=> [0, 1, 3/2, 11/6, 25/12, 137/60, 49/20, 363/140, 761/280, 7129/2520]