Faulhaber's formula: Difference between revisions

Added FreeBASIC
No edit summary
(Added FreeBASIC)
 
(13 intermediate revisions by 8 users not shown)
Line 21:
=={{header|C}}==
{{trans|Modula-2}}
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
Line 189:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 204:
=={{header|C sharp|C#}}==
{{trans|Java}}
<langsyntaxhighlight lang="csharp">using System;
 
namespace FaulhabersFormula {
Line 383:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 399:
{{trans|D}}
Uses C++17
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <numeric>
#include <sstream>
Line 568:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 583:
=={{header|D}}==
{{trans|Kotlin}}
<langsyntaxhighlight Dlang="d">import std.algorithm : fold;
import std.exception : enforce;
import std.format : formattedWrite;
Line 732:
faulhaber(i);
}
}</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 746:
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'math) ;; for bernoulli numbers
(string-delimiter "")
Line 764:
(define (Faulcomp n p)
(printf "Σ(1..%d) n^%d = %d" n p (/ (poly n (Faulhaber p)) (1+ p) )))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 794:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting kernel math math.combinatorics math.extras
math.functions regexp sequences ;
 
Line 812:
: poly>str ( seq -- str ) (poly>str) clean-up ;
 
10 [ dup faulhaber poly>str "%d: %s\n" printf ] each-integer</langsyntaxhighlight>
{{out}}
<pre>
Line 826:
9: 1/10n^10 + 1/2n^9 + 3/4n^8 - 7/10n^6 + 1/2n^4 - 3/20n^2
</pre>
 
=={{header|FreeBASIC}}==
{{trans|C}}
<syntaxhighlight lang="vbnet">Type Fraction
As Integer num
As Integer den
End Type
 
Function Binomial(n As Integer, k As Integer) As Integer
If n < 0 Or k < 0 Then Print "Arguments must be non-negative integers": Exit Function
If n < k Then Print "The second argument cannot be more than the first.": Exit Function
If n = 0 Or k = 0 Then Return 1
Dim As Integer i, num, den
num = 1
For i = k + 1 To n
num *= i
Next i
den = 1
For i = 2 To n - k
den *= i
Next i
Return num / den
End Function
 
Function GCD(n As Integer, d As Integer) As Integer
Return Iif(d = 0, n, GCD(d, n Mod d))
End Function
 
Function makeFrac(n As Integer, d As Integer) As Fraction
Dim As Fraction result
Dim As Integer g
If d = 0 Then
result.num = 0
result.den = 0
Return result
End If
If n = 0 Then
d = 1
Elseif d < 0 Then
n = -n
d = -d
End If
g = Abs(gcd(n, d))
If g > 1 Then
n /= g
d /= g
End If
result.num = n
result.den = d
Return result
End Function
 
Function negateFrac(f As Fraction) As Fraction
Return makeFrac(-f.num, f.den)
End Function
 
Function subFrac(lhs As Fraction, rhs As Fraction) As Fraction
Return makeFrac(lhs.num * rhs.den - lhs.den * rhs.num, rhs.den * lhs.den)
End Function
 
Function multFrac(lhs As Fraction, rhs As Fraction) As Fraction
Return makeFrac(lhs.num * rhs.num, lhs.den * rhs.den)
End Function
 
Function equalFrac(lhs As Fraction, rhs As Fraction) As Integer
Return (lhs.num = rhs.num) And (lhs.den = rhs.den)
End Function
 
Function lessFrac(lhs As Fraction, rhs As Fraction) As Integer
Return (lhs.num * rhs.den) < (rhs.num * lhs.den)
End Function
 
Sub printFrac(f As Fraction)
Print Str(f.num);
If f.den <> 1 Then Print "/" & f.den;
End Sub
 
Function Bernoulli(n As Integer) As Fraction
If n < 0 Then Print "Argument must be non-negative": Exit Function
Dim As Fraction a(16)
Dim As Integer j, m
If (n < 0) Then
a(0).num = 0
a(0).den = 0
Return a(0)
End If
For m = 0 To n
a(m) = makeFrac(1, m + 1)
For j = m To 1 Step -1
a(j - 1) = multFrac(subFrac(a(j - 1), a(j)), makeFrac(j, 1))
Next j
Next m
If n <> 1 Then Return a(0)
Return negateFrac(a(0))
End Function
 
Sub Faulhaber(p As Integer)
Dim As Fraction coeff, q
Dim As Integer j, pwr, sign
Print p & " : ";
q = makeFrac(1, p + 1)
sign = -1
For j = 0 To p
sign = -1 * sign
coeff = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(Binomial(p + 1, j), 1)), Bernoulli(j))
If (equalFrac(coeff, makeFrac(0, 1))) Then Continue For
If j = 0 Then
If Not equalFrac(coeff, makeFrac(1, 1)) Then
If equalFrac(coeff, makeFrac(-1, 1)) Then
Print "-";
Else
printFrac(coeff)
End If
End If
Else
If equalFrac(coeff, makeFrac(1, 1)) Then
Print " + ";
Elseif equalFrac(coeff, makeFrac(-1, 1)) Then
Print " - ";
Elseif lessFrac(makeFrac(0, 1), coeff) Then
Print " + ";
printFrac(coeff)
Else
Print " - ";
printFrac(negateFrac(coeff))
End If
End If
pwr = p + 1 - j
Print Iif(pwr > 1, "n^" & pwr, "n");
Next j
Print
End Sub
 
For i As Integer = 0 To 9
Faulhaber(i)
Next i
 
Sleep</syntaxhighlight>
{{out}}
<pre>Same as C entry.</pre>
 
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Faulhaber}}
 
'''Solution'''
The following function creates the Faulhaber's coefficients up to a given number of rows, according to the [http://www.ww.ingeniousmathstat.org/sites/default/files/Torabi-Dashti-CMJ-2011.pdf paper] of of Mohammad Torabi Dashti:
 
(This is exactly the as than the task [[Faulhaber%27s_triangle#F%C5%8Drmul%C3%A6|Faulhaber's triangle]])
 
[[File:Fōrmulæ - Faulhaber 01.png]]
 
The following function creates the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n:
 
Notes. The -1 index means the last element (-2 is the penultimate element, and so on). So it retrieves the last row of the triangle. |x| is the cardinality (number of elements) of x.
 
(This is exactly the as than the task [[Faulhaber%27s_triangle#F%C5%8Drmul%C3%A6|Faulhaber's triangle]])
 
This function can be used for both symbolic or numeric computation of the polynomial:
 
[[File:Fōrmulæ - Faulhaber 06.png]]
 
To generate the first 10 closed-form expressions, starting with p = 0:
In [https://wiki.formulae.org/Faulhaber this] page you can see the solution of this task.
 
[[File:Fōrmulæ - Faulhaber 07.png]]
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text ([http://wiki.formulae.org/Editing_F%C5%8Drmul%C3%A6_expressions more info]). Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for transportation effects more than visualization and edition.
 
[[File:Fōrmulæ - Faulhaber 08.png]]
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
=={{header|GAP}}==
Straightforward implementation using GAP polynomials, and two different formulas: one based on Stirling numbers of the second kind (sum1, see Python implementation below in this page), and the usual Faulhaber formula (sum2). No optimization is made (one could compute Stirling numbers row by row, or the product in sum1 may be kept from one call to the other). Notice the Bernoulli term in the first formula is here only to correct the value of sum1(0), which is off by one because sum1 computes sums from 0 to n.
 
<langsyntaxhighlight lang="gap">n := X(Rationals, "n");
sum1 := p -> Sum([0 .. p], k -> Stirling2(p, k) * Product([0 .. k], j -> n + 1 - j) / (k + 1)) + 2 * Bernoulli(2 * p + 1);
sum2 := p -> Sum([0 .. p], j -> (-1)^j * Binomial(p + 1, j) * Bernoulli(j) * n^(p + 1 - j)) / (p + 1);
Line 856 ⟶ 1,026:
1/8*n^8+1/2*n^7+7/12*n^6-7/24*n^4+1/12*n^2
1/9*n^9+1/2*n^8+2/3*n^7-7/15*n^5+2/9*n^3-1/30*n
1/10*n^10+1/2*n^9+3/4*n^8-7/10*n^6+1/2*n^4-3/20*n^2</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight Golang="go">package main
 
import (
Line 918 ⟶ 1,088:
fmt.Println()
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 935 ⟶ 1,105:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">import java.util.stream.IntStream
 
class FaulhabersFormula {
Line 1,076 ⟶ 1,246:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 1,091 ⟶ 1,261:
=={{header|Haskell}}==
====Bernouilli polynomials====
<langsyntaxhighlight Haskelllang="haskell">import Data.Ratio ((%), numerator, denominator)
import Data.List (intercalate, transpose)
import Data.Bifunctor (bimap)
Line 1,193 ⟶ 1,363:
unsignedLength xs =
let l = length xs
in bool (bool l (l - 1) ('-' == head xs)) 0 (0 == l)</langsyntaxhighlight>
{{Out}}
<pre>0 -> n
Line 1,210 ⟶ 1,380:
Implementation:
 
<langsyntaxhighlight Jlang="j">Bsecond=:verb define"0
+/,(<:*(_1^[)*!*(y^~1+[)%1+])"0/~i.1x+y
)
Line 1,218 ⟶ 1,388:
Faul=:adverb define
(0,|.(%m+1x) * (_1x&^ * !&(m+1) * Bfirst) i.1+m)&p.
)</langsyntaxhighlight>
 
Task example:
 
<langsyntaxhighlight Jlang="j"> 0 Faul
0 1x&p.
1 Faul
Line 1,241 ⟶ 1,411:
0 _1r30 0 2r9 0 _7r15 0 2r3 1r2 1r9&p.
9 Faul
0 0 _3r20 0 1r2 0 _7r10 0 3r4 1r2 1r10&p.</langsyntaxhighlight>
 
Double checking our work:
 
<langsyntaxhighlight Jlang="j"> Fcheck=: dyad def'+/(1+i.y)^x'"0
9 Faul i.5
0 1 513 20196 282340
Line 1,253 ⟶ 1,423:
0 1 5 14 30
2 Fcheck i.5
0 1 5 14 30</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|Kotlin}}
{{works with|Java|8}}
<langsyntaxhighlight Javalang="java">import java.util.Arrays;
import java.util.stream.IntStream;
 
Line 1,399 ⟶ 1,569:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 1,411 ⟶ 1,581:
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|jq}}==
{{works with|jq}}
'''Works with gojq, the Go implementation of jq, and with fq'''
 
The following assumes the following rational arithmetic functions
as provided by the jq "rational" module at [[Arithmetic/Rational#jq]]:
 
* r/2 (constructor)
* requal/2 (equality)
* rlessthan/1
* rminus/1
* rminus/2 (subtraction)
* rmult/0 and rmult/2 (multiplication)
 
In addition, the pretty-printing function defined here (rpp) assumes
rationals are JSON objects of the form {n,d}
<syntaxhighlight lang=jq>
include "rational" {search: "."}; # see [[Arithmetic/Rational#jq]]:
 
# Preliminaries
# for gojq
def idivide($j):
. as $i
| ($i % $j) as $mod
| ($i - $mod) / $j ;
 
# use idivide for precision
def binomial(n; k):
if k > n / 2 then binomial(n; n-k)
else reduce range(1; k+1) as $i (1; . * (n - $i + 1) | idivide($i))
end;
 
# pretty print a Rational assumed to have the {n,d} form
def rpp:
if .n == 0 then "0"
elif .d == 1 then .n | tostring
else "\(.n)/\(.d)"
end;
 
# The following definition reflects the "modern view" that B(1) is 1 // 2
def bernoulli:
if type != "number" or . < 0 then "bernoulli must be given a non-negative number vs \(.)" | error
else . as $n
| reduce range(0; $n+1) as $i ([];
.[$i] = r(1; $i + 1)
| reduce range($i; 0; -1) as $j (.;
.[$j-1] = rmult($j; rminus(.[$j-1]; .[$j])) ) )
| .[0] # the modern view
end;
 
 
# The task
def faulhaber($p):
# The traditional view:
def bernouilli($n):
$n | bernouilli | if $n==1 then rminus else . end;
r(1; $p+1) as $q
| { sign: -1 }
| reduce range(0; 1+$p) as $j (.;
.sign *= -1
| r(binomial($p+1; $j); 1) as $b
| ([$q, .sign, $b, ($j|bernoulli)] | rmult) as $coeff
| if requal($coeff; r(0;1))|not
then .emit +=
(if $j == 0
then (if requal($coeff; r( 1;1)) then ""
elif requal($coeff; r(-1;1)) then "-"
else "\($coeff|rpp) " end)
else (if requal($coeff; r(1;1)) then " + "
elif requal($coeff; r(-1;1)) then " - "
elif r(0;1)|rlessthan($coeff) then " + \($coeff|rpp) "
else " - \($coeff|rminus|rpp) "
end)
end)
| ($p + 1 - $j) as $pwr
| .emit += (if 1 < $pwr then "n^\($pwr)" else "n" end)
else .
end )
| .emit ;
 
range(0;10) | "\(.) : \(faulhaber(.))"
</syntaxhighlight>
{{output}}
<pre>
0 : n
1 : 1/2 n^2 - 1/2 n
2 : 1/3 n^3 - 1/2 n^2 + 1/6 n
3 : 1/4 n^4 - 1/2 n^3 + 1/4 n^2
4 : 1/5 n^5 - 1/2 n^4 + 1/3 n^3 - 1/30 n
5 : 1/6 n^6 - 1/2 n^5 + 5/12 n^4 - 1/12 n^2
6 : 1/7 n^7 - 1/2 n^6 + 1/2 n^5 - 1/6 n^3 + 1/42 n
7 : 1/8 n^8 - 1/2 n^7 + 7/12 n^6 - 7/24 n^4 + 1/12 n^2
8 : 1/9 n^9 - 1/2 n^8 + 2/3 n^7 - 7/15 n^5 + 2/9 n^3 - 1/30 n
9 : 1/10 n^10 - 1/2 n^9 + 3/4 n^8 - 7/10 n^6 + 1/2 n^4 - 3/20 n^2
</pre>
 
=={{header|Julia}}==
Line 1,416 ⟶ 1,683:
 
'''Module''':
<langsyntaxhighlight lang="julia">module Faulhaber
 
function bernoulli(n::Integer)
Line 1,456 ⟶ 1,723:
end
 
end # module Faulhaber</langsyntaxhighlight>
 
'''Main''':
<syntaxhighlight lang ="julia">Faulhaber.formula.(1:10)</langsyntaxhighlight>
 
{{out}}
Line 1,475 ⟶ 1,742:
=={{header|Kotlin}}==
As Kotlin doesn't have support for rational numbers built in, a cut-down version of the Frac class in the Arithmetic/Rational task has been used in order to express the polynomial coefficients as fractions.
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
Line 1,593 ⟶ 1,860:
fun main(args: Array<String>) {
for (i in 0..9) faulhaber(i)
}</langsyntaxhighlight>
 
{{out}}
Line 1,611 ⟶ 1,878:
=={{header|Lua}}==
{{trans|C}}
<langsyntaxhighlight lang="lua">function binomial(n,k)
if n<0 or k<0 or n<k then return -1 end
if n==0 or k==0 then return 1 end
Line 1,756 ⟶ 2,023:
for i=0,9 do
faulhaber(i)
end</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 1,770 ⟶ 2,037:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[Faulhaber]
Faulhaber[n_, 0] := n
Faulhaber[n_, p_] := n^(p + 1)/(p + 1) + 1/2 n^p + Sum[BernoulliB[k]/k! p!/(p - k + 1)! n^(p - k + 1), {k, 2, p}]
Table[{p, Faulhaber[n, p]}, {p, 0, 9}] // Grid</langsyntaxhighlight>
{{out}}
<pre>0 n
Line 1,787 ⟶ 2,054:
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">sum1(p):=sum(stirling2(p,k)*pochhammer(n-k+1,k+1)/(k+1),k,0,p)$
sum2(p):=sum((-1)^j*binomial(p+1,j)*bern(j)*n^(p-j+1),j,0,p)/(p+1)$
 
Line 1,793 ⟶ 2,060:
[0,0,0,0,0,0,0,0,0,0]
 
for p from 0 thru 9 do print(expand(sum2(p)));</langsyntaxhighlight>
{{out}}
<pre>
Line 1,810 ⟶ 2,077:
=={{header|Modula-2}}==
{{trans|C#}}
<langsyntaxhighlight lang="modula2">MODULE Faulhaber;
FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE;
FROM FormatString IMPORT FormatString;
Line 1,991 ⟶ 2,258:
END;
ReadChar
END Faulhaber.</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 2,006 ⟶ 2,273:
=={{header|Nim}}==
{{trans|Kotlin}}
<langsyntaxhighlight Nimlang="nim">import math, rationals
 
type
Line 2,079 ⟶ 2,346:
 
for n in 0..9:
echo n, ": ", faulhaber(n)</langsyntaxhighlight>
 
{{out}}
Line 2,101 ⟶ 2,368:
It's not worth using Bernoulli numbers in PARI/GP, because too much cleaning if you are avoiding "dirty" (but correct) result.<br>
Note: Find ssubstr() function here on RC.
<langsyntaxhighlight lang="parigp">
\\ Using "Faulhaber's" formula based on Bernoulli numbers. aev 2/7/17
\\ In str string replace all occurrences of the search string ssrch with the replacement string srepl. aev 3/8/16
Line 2,133 ⟶ 2,400:
{\\ Testing:
for(i=0,9, Faulhaber2(i))}
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 2,151 ⟶ 2,418:
This version is using the sums of pth powers formula from [[wp:Bernoulli_polynomials| Bernoulli polynomials]].
It has small, simple and clear code, and produces instant result.
<langsyntaxhighlight lang="parigp">
\\ Using a formula based on Bernoulli polynomials. aev 2/5/17
Faulhaber1(m)={
Line 2,162 ⟶ 2,429:
{\\ Testing:
for(i=0,9, Faulhaber1(i))}
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 2,177 ⟶ 2,444:
> ##
*** last result computed in 0 ms
</pre>
 
=={{header|Pascal}}==
A console program that runs under Lazarus or Delphi. Does not make use of Bernoulli numbers.
<syntaxhighlight lang="pascal">
program Faulhaber;
 
{$IFDEF FPC} // Lazarus
{$MODE Delphi} // ensure Lazarus accepts Delphi-style code
{$ASSERTIONS+} // by default, Lazarus does not compile 'Assert' statements
{$ELSE} // Delphi
{$APPTYPE CONSOLE}
{$ENDIF}
 
uses SysUtils;
 
type TRational = record
Num, Den : integer; // where Den > 0 and Num, Den are coprime
end;
 
const
ZERO : TRational = ( Num: 0; Den : 1);
HALF : TRational = ( Num: 1; Den : 2);
 
// Construct rational a/b, assuming b > 0.
function Rational( const a, b : integer) : TRational;
var
t, x, y : integer;
begin
if b <= 0 then raise SysUtils.Exception.Create( 'Denominator must be > 0');
// Find HCF of a and b (Euclid's algorithm) and cancel it out.
x := Abs(a);
y := b;
while y <> 0 do begin
t := x mod y;
x := y;
y := t;
end;
result.Num := a div x;
result.Den := b div x
end;
 
function Prod( r, s : TRational) : TRational; // result := r*s
begin
result := Rational( r.Num*s.Num, r.Den*s.Den);
end;
 
procedure DecRat( var r : TRational;
const s : TRational); // r := r - s
begin
r := Rational( r.Num*s.Den - s.Num*r.Den, r.Den * s.Den);
end;
 
// Write a term such as ' - (7/10)n^6' to the console.
procedure WriteTerm( coeff : TRational;
index : integer;
printPlus : boolean);
begin
if Coeff.Num = 0 then exit;
with coeff do begin
if Num < 0 then Write(' - ')
else if printPlus then Write(' + ');
// Put brackets round a fractional coefficient
if (Den > 1) then Write('(');
// If coefficient is 1, don't write it
if (Den > 1) or (Abs(Num) > 1) then Write( Abs(Num));
// Write denominator if it's not 1
if (Den > 1) then Write('/', Den, ')');
end;
Write('n');
if index > 1 then Write('^', index);
end;
 
{-------------------------------------------------------------------------------
Main routine. Calculation of Faulhaber polynomials
F_p(n) = 1^p + 2^p + ... + n^p, p = 0, 1, ..., p_max
}
var
p_max : integer;
c : array of array of TRational;
i, j, p : integer;
coeff_of_n : TRational;
begin
// User types program name, optionally followed by maximum power p (defaults to 9)
if ParamCount = 0 then p_max := 9
else p_max := SysUtils.StrToInt( ParamStr(1));
 
// c[p, i] is coefficient of n^i in the polynomial F_p(n).
// Initialize all coefficients to 0.
SetLength( c, p_max + 1, p_max + 2);
for i := 0 to p_max do
for j := 0 to p_max + 1 do
c[i, j] := ZERO;
 
c[0, 1] := Rational(1, 1); // F_0(n) = n, special case
for p := 1 to p_max do begin
// Initialize calculation of coefficient of n, needed if p is even.
// If p is odd, still calculate it as a check on the working (should be 0).
// Calculation uses the fact that F_p(1) = 1.
coeff_of_n := Rational(1, 1);
 
c[p, p+1] := Rational(1, p + 1);
DecRat( coeff_of_n, c[p, p + 1]);
c[p, p] := HALF;
DecRat( coeff_of_n, c[p, p]);
i := p - 1;
while (i >= 2) do begin
c[p, i] := Prod( Rational(p, i), c[p - 1, i - 1]);
DecRat( coeff_of_n, c[p, i]);
dec(i, 2);
end;
if i = 1 then // p is even
c[p, 1] := coeff_of_n // = the Bernoulli number B_p
else // p is odd
Assert( coeff_of_n.Num = 0); // just checking
end; // for p
 
// Print the result
for p := 0 to p_max do begin
Write( 'F_', p, '(n) = ');
for j := p + 1 downto 1 do WriteTerm( c[p, j], j, j <= p);
WriteLn;
end;
end.
</syntaxhighlight>
{{out}}
<pre>
F_0(n) = n
F_1(n) = (1/2)n^2 + (1/2)n
F_2(n) = (1/3)n^3 + (1/2)n^2 + (1/6)n
F_3(n) = (1/4)n^4 + (1/2)n^3 + (1/4)n^2
F_4(n) = (1/5)n^5 + (1/2)n^4 + (1/3)n^3 - (1/30)n
F_5(n) = (1/6)n^6 + (1/2)n^5 + (5/12)n^4 - (1/12)n^2
F_6(n) = (1/7)n^7 + (1/2)n^6 + (1/2)n^5 - (1/6)n^3 + (1/42)n
F_7(n) = (1/8)n^8 + (1/2)n^7 + (7/12)n^6 - (7/24)n^4 + (1/12)n^2
F_8(n) = (1/9)n^9 + (1/2)n^8 + (2/3)n^7 - (7/15)n^5 + (2/9)n^3 - (1/30)n
F_9(n) = (1/10)n^10 + (1/2)n^9 + (3/4)n^8 - (7/10)n^6 + (1/2)n^4 - (3/20)n^2
</pre>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use 5.014;
use Math::Algebra::Symbols;
 
Line 2,222 ⟶ 2,626:
foreach my $i (0 .. 9) {
say "$i: ", faulhaber_s_formula($i);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,239 ⟶ 2,643:
=={{header|Phix}}==
{{trans|C#}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>include builtins\pfrac.e -- (0.8.0+)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
 
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">pfrac</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span> <span style="color: #000080;font-style:italic;">-- (0.8.0+)</span>
function bernoulli(integer n)
sequence a = {}
<span style="color: #008080;">function</span> <span style="color: #000000;">bernoulli</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
for m=0 to n do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
a = append(a,{1,m+1})
<span style="color: #008080;">for</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
for j=m to 1 by -1 do
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">})</span>
a[j] = frac_mul({j,1},frac_sub(a[j+1],a[j]))
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">m</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">frac_mul</span><span style="color: #0000FF;">({</span><span style="color: #000000;">j</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span><span style="color: #000000;">frac_sub</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">],</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]))</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
if n!=1 then return a[1] end if
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return frac_uminus(a[1])
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">frac_uminus</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
function binomial(integer n, k)
if n<0 or k<0 or n<k then ?9/0 end if
<span style="color: #008080;">function</span> <span style="color: #000000;">binomial</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">)</span>
if n=0 or k=0 then return 1 end if
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #000000;">k</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #000000;">n</span><span style="color: #0000FF;"><</span><span style="color: #000000;">k</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">9</span><span style="color: #0000FF;">/</span><span style="color: #000000;">0</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
integer num = 1,
<span style="color: #008080;">if</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">or</span> <span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">return</span> <span style="color: #000000;">1</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
denom = 1
<span style="color: #004080;">integer</span> <span style="color: #000000;">num</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span>
for i=k+1 to n do
<span style="color: #000000;">denom</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
num *= i
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">k</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">num</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">i</span>
for i=2 to n-k do
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
denom *= i
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">k</span> <span style="color: #008080;">do</span>
end for
<span style="color: #000000;">denom</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">i</span>
return num / denom
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end function
<span style="color: #008080;">return</span> <span style="color: #000000;">num</span> <span style="color: #0000FF;">/</span> <span style="color: #000000;">denom</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
procedure faulhaber(integer p)
string res = sprintf("%d : ", p)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">faulhaber</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
frac q = {1, p+1}
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%d : "</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">)</span>
for j=0 to p do
<span style="color: #000000;">frac</span> <span style="color: #000000;">q</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}</span>
frac bj = bernoulli(j)
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">p</span> <span style="color: #008080;">do</span>
if frac_ne(bj,frac_zero) then
<span style="color: #000000;">frac</span> <span style="color: #000000;">bj</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">bernoulli</span><span style="color: #0000FF;">(</span><span style="color: #000000;">j</span><span style="color: #0000FF;">)</span>
frac coeff = frac_mul({binomial(p+1,j),p+1},bj)
<span style="color: #008080;">if</span> <span style="color: #000000;">frac_ne</span><span style="color: #0000FF;">(</span><span style="color: #000000;">bj</span><span style="color: #0000FF;">,</span><span style="color: #000000;">frac_zero</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
string s = frac_sprint(coeff)
<span style="color: #000000;">frac</span> <span style="color: #000000;">coeff</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">frac_mul</span><span style="color: #0000FF;">({</span><span style="color: #000000;">binomial</span><span style="color: #0000FF;">(</span><span style="color: #000000;">p</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">),</span><span style="color: #000000;">p</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">},</span><span style="color: #000000;">bj</span><span style="color: #0000FF;">)</span>
if j=0 then
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">frac_sprint</span><span style="color: #0000FF;">(</span><span style="color: #000000;">coeff</span><span style="color: #0000FF;">)</span>
if s="1" then
<span style="color: #008080;">if</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
s = ""
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">=</span><span style="color: #008000;">"1"</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
else
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
if s[1]='-' then
<span s[1..1] style= "color: - #008080;">else</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #008000;">'-'</span> <span style="color: #008080;">then</span>
else
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">" - "</span>
s[1..0] = " + "
end if<span style="color: #008080;">else</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">..</span><span style="color: #000000;">0</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">" + "</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
res &= s&"n"
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
integer pwr = p+1-j
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">&</span><span style="color: #008000;">"n"</span>
if pwr>1 then
<span style="color: #004080;">integer</span> <span style="color: #000000;">pwr</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">p</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">-</span><span style="color: #000000;">j</span>
res &= sprintf("^%d", pwr)
<span style="color: #008080;">if</span> <span style="color: #000000;">pwr</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
end if
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"^%d"</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">pwr</span><span style="color: #0000FF;">)</span>
end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
printf(1,"%s\n",{res})
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
end procedure
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
for i=0 to 9 do
faulhaber(i)
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">9</span> <span style="color: #008080;">do</span>
end for</lang>
<span style="color: #000000;">faulhaber</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,325 ⟶ 2,732:
 
 
<langsyntaxhighlight lang="python">from fractions import Fraction
 
def nextu(a):
Line 2,387 ⟶ 2,794:
 
for i, p in enumerate(sumpol(10)):
print(i, ":", polstr(p))</langsyntaxhighlight>
 
{{out}}
Line 2,405 ⟶ 2,812:
Racket will simplify rational numbers; if this code simplifies the expressions too much for your tastes (e.g. you like <code>1/1 * (n)</code>) then tweak the simplify... clauses to taste.
 
<langsyntaxhighlight lang="racket">#lang racket/base
 
(require racket/match
Line 2,461 ⟶ 2,868:
(for ((p (in-range 0 (add1 9))))
(printf "f(~a) = ~a~%" p (expression->infix-string (faulhaber p))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,480 ⟶ 2,887:
(formerly Perl 6)
{{works with|Rakudo|2018.04.01}}
<syntaxhighlight lang="raku" perl6line>sub bernoulli_number($n) {
 
return 1/2 if $n == 1;
Line 2,518 ⟶ 2,925:
for 0..9 -> $p {
say "f($p) = ", faulhaber_s_formula($p);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,531 ⟶ 2,938:
f(8) = 1/9 * (n^9 + (9/2)*n^8 + (6/1)*n^7 + (-21/5)*n^5 + (2/1)*n^3 + (-3/10)*n)
f(9) = 1/10 * (n^10 + (5/1)*n^9 + (15/2)*n^8 + (-7/1)*n^6 + (5/1)*n^4 + (-3/2)*n^2)
</pre>
 
=={{header|RPL}}==
{{works with|HP|49}}
≪ → p
≪ 0
p 0 '''FOR''' m
p 1 + m 1 + COMB
p m - IBERNOULLI
'''IF''' LASTARG 1 == '''THEN''' NEG '''END'''
* EVAL + 'n' *
-1 '''STEP'''
p 1 + / EXPAN
≫ ≫ '<span style="color:blue>FAULH</span>' STO
 
≪ P <span style="color:blue>FAULH</span> ≫ 'P' 0 9 1 SEQ
{{out}}
<pre>
1: {'n' '1/2n^2+1/2n' '1/3n^3+1/2n^2+1/6n' '1/4n^4+1/2n^3+1/4n^2' '1/5n^5+1/2n^4+1/3n^3-1/30n' '1/6n^6+1/2n^5+5/12n^4-1/12n^2' '1/7n^7+1/2n^6+1/2n^5-1/6n^3+1/42n' '1/8n^8+1/2n^7+7/12n^6-7/24n^4+1/12n^2' '1/9n^9+1/2n^8+2/3n^7-7/15n^5+2/9n^3-1/30n' '1/10n^10+1/2n^9+3/4n^8-7/10n^6+1/2n^4-3/20n^2'}
</pre>
 
=={{header|Ruby}}==
{{trans|C}}
<langsyntaxhighlight lang="ruby">def binomial(n,k)
if n < 0 or k < 0 or n < k then
return -1
Line 2,622 ⟶ 3,048:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 2,637 ⟶ 3,063:
=={{header|Scala}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">import scala.math.Ordering.Implicits.infixOrderingOps
 
abstract class Frac extends Comparable[Frac] {
Line 2,807 ⟶ 3,233:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 2,821 ⟶ 3,247:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func faulhaber_formula(p) {
<lang ruby>const AnyNum = require('Math::AnyNum')
const Poly = require('Math::Polynomial')
 
Poly.string_config(Hash(
fold_sign => true, prefix => "",
suffix => "", variable => "n"
))
 
func anynum(n) {
AnyNum.new(n.as_rat)
}
 
func faulhaber_formula(p) {
(p+1).of { |j|
Poly.monomial(p - j + 1 => 1) * bernoulli(j) * binomial(p+1, j)\
}.sum / (p+1)
.mul_const(anynum(bernoulli(j)))\
.mul_const(anynum(binomial(p+1, j)))
}.reduce(:add).div_const(p+1)
}
 
for p in (^10) {
printf("%2d: %s\n", p, faulhaber_formula(p))
}</langsyntaxhighlight>
{{out}}
<pre>
0: nx
1: 1/2 n*x^2 + 1/2 n*x
2: 1/3 n*x^3 + 1/2 n*x^2 + 1/6 n*x
3: 1/4 n*x^4 + 1/2 n*x^3 + 1/4 n*x^2
4: 1/5 n*x^5 + 1/2 n*x^4 + 1/3 n*x^3 - 1/30 n*x
5: 1/6 n*x^6 + 1/2 n*x^5 + 5/12 n*x^4 - 1/12 n*x^2
6: 1/7 n*x^7 + 1/2 n*x^6 + 1/2 n*x^5 - 1/6 n*x^3 + 1/42 n*x
7: 1/8 n*x^8 + 1/2 n*x^7 + 7/12 n*x^6 - 7/24 n*x^4 + 1/12 n*x^2
8: 1/9 n*x^9 + 1/2 n*x^8 + 2/3 n*x^7 - 7/15 n*x^5 + 2/9 n*x^3 - 1/30 n*x
9: 1/10 n*x^10 + 1/2 n*x^9 + 3/4 n*x^8 - 7/10 n*x^6 + 1/2 n*x^4 - 3/20 n*x^2
</pre>
 
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<langsyntaxhighlight lang="vbnet">Module Module1
Function Gcd(a As Long, b As Long)
If b = 0 Then
Line 3,022 ⟶ 3,434:
Next
End Sub
End Module</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 3,039 ⟶ 3,451:
{{libheader|Wren-math}}
{{libheader|Wren-rat}}
<langsyntaxhighlight ecmascriptlang="wren">import "./math" for Int
import "./rat" for Rat
 
var bernoulli = Fn.new { |n|
Line 3,091 ⟶ 3,503:
}
 
for (i in 0..9) faulhaber.call(i)</langsyntaxhighlight>
 
{{out}}
Line 3,110 ⟶ 3,522:
{{libheader|GMP}} GNU Multiple Precision Arithmetic Library
Uses code from the Bernoulli numbers task (copied here).
<langsyntaxhighlight lang="zkl">var [const] BN=Import("zklBigNum"); // libGMP (GNU MP Bignum Library)
 
fcn faulhaberFormula(p){ //-->(Rational,Rational...)
[p..0,-1].pump(List(),'wrap(k){ B(k)*BN(p+1).binomial(k) })
.apply('*(Rational(1,p+1)))
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach p in (10){
println("F(%d) --> %s".fmt(p,polyRatString(faulhaberFormula(p))))
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">class Rational{ // Weenie Rational class, can handle BigInts
fcn init(_a,_b){ var a=_a, b=_b; normalize(); }
fcn toString{
Line 3,142 ⟶ 3,554:
}
fcn __opDiv(n){ self(a*n.b,b*n.a) } // Rat / Rat
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fcn B(N){ // calculate Bernoulli(n) --> Rational
var A=List.createLong(100,0); // aka static aka not thread safe
foreach m in (N+1){
Line 3,159 ⟶ 3,571:
if(str[0]=="+") str[1,*]; // leave leading space
else String("-",str[2,*]);
}</langsyntaxhighlight>
{{out}}
<pre>
2,122

edits