Jump to content

Faulhaber's triangle: Difference between revisions

(Added Wren)
Line 1,857:
-1/30 -0 2/9 -0 -7/15 -0 2/3 1/2 1/9
-0 -3/20 -0 1/2 -0 -7/10 -0 3/4 1/2 1/10</pre>
 
=={{header|Nim}}==
{{libheader|bignum}}
For the task, we could use the standard module “rationals” but for the extra task we need big numbers (and big rationals). We use third party module “bignum” for this purpose.
<lang Nim>import algorithm, math, strutils
import bignum
 
type FaulhaberSequence = seq[Rat]
 
#---------------------------------------------------------------------------------------------------
 
func bernoulli(n: Natural): Rat =
## Return nth Bernoulli coefficient.
 
var a = newSeq[Rat](n + 1)
for m in 0..n:
a[m] = newRat(1, m + 1)
for k in countdown(m, 1):
a[k - 1] = (a[k - 1] - a[k]) * k
result = if n != 1: a[0] else: -a[0]
 
#---------------------------------------------------------------------------------------------------
 
func faulhaber(n: Natural): FaulhaberSequence =
## Return nth Faulhaber sequence (high degree first).
 
var a = newRat(1, n + 1)
var sign = -1
for k in 0..n:
sign = -sign
result.add(a * sign * binom(n + 1, k) * bernoulli(k))
 
#---------------------------------------------------------------------------------------------------
 
proc display(fs: FaulhaberSequence) =
## Return the string representing a Faulhaber sequence.
 
var str = ""
for i, coeff in reversed(fs):
str.addSep(" ", 0)
str.add(($coeff).align(6))
echo str
 
#---------------------------------------------------------------------------------------------------
 
func evaluate(fs: FaulhaberSequence; n: int): Rat =
## Evaluate the polynomial associated to a sequence for value "n".
 
result = newRat(0)
for coeff in fs:
result = result * n + coeff
result *= n
 
#———————————————————————————————————————————————————————————————————————————————————————————————————
 
for n in 0..9:
display(faulhaber(n))
 
echo ""
let fs18 = faulhaber(17) # 18th row.
echo fs18.evaluate(1000)</lang>
 
{{out}}
<pre> 1
1/2 1/2
1/6 1/2 1/3
0 1/4 1/2 1/4
-1/30 0 1/3 1/2 1/5
0 -1/12 0 5/12 1/2 1/6
1/42 0 -1/6 0 1/2 1/2 1/7
0 1/12 0 -7/24 0 7/12 1/2 1/8
-1/30 0 2/9 0 -7/15 0 2/3 1/2 1/9
0 -3/20 0 1/2 0 -7/10 0 3/4 1/2 1/10
 
56056972216555580111030077961944183400198333273050000</pre>
 
=={{header|Perl}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.