1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- #!/usr/bin/ruby
- # Daniel "Trizen" Șuteu
- # License: GPLv3
- # Date: 07 February 2017
- # https://github.com/trizen
- # Generation of Faulhaber's triangle.
- # Each row of the triangle represents the coefficients
- # for the sum 1^p + 2^p + 3^p + ... + n^p.
- # For example, the third row is the solution for:
- # 1^2 + 2^2 + 3^2 + ... + n^2
- #
- # which can be written as:
- # 1/3 * (1*n^3 + 3/2*n^2 + 1/2*n^1)
- # In general, we have:
- # 1^p + 2^p + 3^p + ... + n^p
- #
- # is equal with:
- # 1/(p+1) * (F[0] * n^(p+1) + F[1] * n^p + F[2] * n^(p-1) + ... + F[p] * n^1)
- # See also:
- # https://en.wikipedia.org/wiki/Faulhaber%27s_formula
- # Inspired by John Conway:
- # https://www.youtube.com/watch?v=Uy1B_eGXQ0g
- func faulhaber_triangle(p) {
- gather {
- for j in (0 .. p) {
- take(binomial(p+1, j) * bernoulli(j))
- }
- }
- }
- for p in (0 .. 11) {
- say faulhaber_triangle(p).map{ '%6s' % .as_rat }.join
- }
- __END__
- 1
- 1 1
- 1 3/2 1/2
- 1 2 1 0
- 1 5/2 5/3 0 -1/6
- 1 3 5/2 0 -1/2 0
- 1 7/2 7/2 0 -7/6 0 1/6
- 1 4 14/3 0 -7/3 0 2/3 0
- 1 9/2 6 0 -21/5 0 2 0 -3/10
- 1 5 15/2 0 -7 0 5 0 -3/2 0
- 1 11/2 55/6 0 -11 0 11 0 -11/2 0 5/6
- 1 6 11 0 -33/2 0 22 0 -33/2 0 5 0
|