Faulhaber's formula: Difference between revisions

Added EchoLisp
m (→‎{{header|Sidef}}: Cached the "bernoulli_number" function)
(Added EchoLisp)
Line 7:
;See also
* [https://en.wikipedia.org/wiki/Bernoulli_number Bernoulli numbers] and [https://en.wikipedia.org/wiki/Binomial_coefficient binomial coefficients] on Wikipedia.
 
 
=={{header|EchoLisp}}==
<lang scheme>
(lib 'math) ;; for bernoulli numbers
(string-delimiter "")
 
;; returns list of polynomial coefficients
(define (Faulhaber p)
(cons 0
(for/list ([k (in-range p -1 -1)])
(* (Cnp (1+ p) k) (bernoulli k)))))
 
;; prints formal polynomial
(define (task (pmax 10))
(for ((p pmax))
(writeln p '→ (/ 1 (1+ p)) '* (poly->string 'n (Faulhaber p)))))
;; extra credit - compute sums
(define (Faulcomp n p)
(printf "Σ(1..%d) n^%d = %d" n p (/ (poly n (Faulhaber p)) (1+ p) )))
</lang>
{{out}}
<pre>
(task)
0 → 1 * n
1 → 1/2 * n^2 + n
2 → 1/3 * n^3 + 3/2 n^2 + 1/2 n
3 → 1/4 * n^4 + 2 n^3 + n^2
4 → 1/5 * n^5 + 5/2 n^4 + 5/3 n^3 -1/6 n
5 → 1/6 * n^6 + 3 n^5 + 5/2 n^4 -1/2 n^2
6 → 1/7 * n^7 + 7/2 n^6 + 7/2 n^5 -7/6 n^3 + 1/6 n
7 → 1/8 * n^8 + 4 n^7 + 14/3 n^6 -7/3 n^4 + 2/3 n^2
8 → 1/9 * n^9 + 9/2 n^8 + 6 n^7 -21/5 n^5 + 2 n^3 -3/10 n
9 → 1/10 * n^10 + 5 n^9 + 15/2 n^8 -7 n^6 + 5 n^4 -3/2 n^2
 
(Faulcomp 100 2)
Σ(1..100) n^2 = 338350
(Faulcomp 100 1)
Σ(1..100) n^1 = 5050
 
(lib 'bigint)
(Faulcomp 100 9)
Σ(1..100) n^9 = 10507499300049998000
 
;; check it ...
(for/sum ((n 101)) (expt n 9))
→ 10507499300049998500
</pre>