-
Notifications
You must be signed in to change notification settings - Fork 0
/
faulhaber_s_triangle.sf
55 lines (45 loc) · 1.35 KB
/
faulhaber_s_triangle.sf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/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