faulhaber_s_triangle.sf 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # License: GPLv3
  4. # Date: 07 February 2017
  5. # https://github.com/trizen
  6. # Generation of Faulhaber's triangle.
  7. # Each row of the triangle represents the coefficients
  8. # for the sum 1^p + 2^p + 3^p + ... + n^p.
  9. # For example, the third row is the solution for:
  10. # 1^2 + 2^2 + 3^2 + ... + n^2
  11. #
  12. # which can be written as:
  13. # 1/3 * (1*n^3 + 3/2*n^2 + 1/2*n^1)
  14. # In general, we have:
  15. # 1^p + 2^p + 3^p + ... + n^p
  16. #
  17. # is equal with:
  18. # 1/(p+1) * (F[0] * n^(p+1) + F[1] * n^p + F[2] * n^(p-1) + ... + F[p] * n^1)
  19. # See also:
  20. # https://en.wikipedia.org/wiki/Faulhaber%27s_formula
  21. # Inspired by John Conway:
  22. # https://www.youtube.com/watch?v=Uy1B_eGXQ0g
  23. func faulhaber_triangle(p) {
  24. gather {
  25. for j in (0 .. p) {
  26. take(binomial(p+1, j) * bernoulli(j))
  27. }
  28. }
  29. }
  30. for p in (0 .. 11) {
  31. say faulhaber_triangle(p).map{ '%6s' % .as_rat }.join
  32. }
  33. __END__
  34. 1
  35. 1 1
  36. 1 3/2 1/2
  37. 1 2 1 0
  38. 1 5/2 5/3 0 -1/6
  39. 1 3 5/2 0 -1/2 0
  40. 1 7/2 7/2 0 -7/6 0 1/6
  41. 1 4 14/3 0 -7/3 0 2/3 0
  42. 1 9/2 6 0 -21/5 0 2 0 -3/10
  43. 1 5 15/2 0 -7 0 5 0 -3/2 0
  44. 1 11/2 55/6 0 -11 0 11 0 -11/2 0 5/6
  45. 1 6 11 0 -33/2 0 22 0 -33/2 0 5 0