Faulhaber's formula: Difference between revisions

Add Factor
m (added closing symbol (:) to section headers.)
(Add Factor)
Line 793:
</pre>
 
=={{header|Factor}}==
<lang factor>USING: formatting kernel math math.combinatorics math.extras
math.functions regexp sequences ;
 
: faulhaber ( p -- seq )
1 + dup recip swap dup <iota>
[ [ nCk ] [ -1 swap ^ ] [ bernoulli ] tri * * * ] 2with map ;
 
: (poly>str) ( seq -- str )
reverse [ 1 + "%un^%d" sprintf ] map-index reverse " + " join ;
 
: clean-up ( str -- str' )
R/ n\^1\z/ "n" re-replace ! Change n^1 to n.
R/ 1n/ "n" re-replace ! Change 1n to n.
R/ \+ -/ "- " re-replace ! Change + - to - .
R/ [+-] 0n(\^\d+ )?/ "" re-replace ; ! Remove terms of zero.
 
: poly>str ( seq -- str ) (poly>str) clean-up ;
 
10 [ dup faulhaber poly>str "%d: %s\n" printf ] each-integer</lang>
{{out}}
<pre>
0: n
1: 1/2n^2 + 1/2n
2: 1/3n^3 + 1/2n^2 + 1/6n
3: 1/4n^4 + 1/2n^3 + 1/4n^2
4: 1/5n^5 + 1/2n^4 + 1/3n^3 - 1/30n
5: 1/6n^6 + 1/2n^5 + 5/12n^4 - 1/12n^2
6: 1/7n^7 + 1/2n^6 + 1/2n^5 - 1/6n^3 + 1/42n
7: 1/8n^8 + 1/2n^7 + 7/12n^6 - 7/24n^4 + 1/12n^2
8: 1/9n^9 + 1/2n^8 + 2/3n^7 - 7/15n^5 + 2/9n^3 - 1/30n
9: 1/10n^10 + 1/2n^9 + 3/4n^8 - 7/10n^6 + 1/2n^4 - 3/20n^2
</pre>
 
=={{header|GAP}}==
1,808

edits