Faulhaber's formula: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Phix}}: added syntax colouring, marked p2js compatible)
m (syntax highlighting fixup automation)
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 838:
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/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:
fmt.Println()
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 935:
=={{header|Groovy}}==
{{trans|Java}}
<langsyntaxhighlight lang="groovy">import java.util.stream.IntStream
 
class FaulhabersFormula {
Line 1,076:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 1,091:
=={{header|Haskell}}==
====Bernouilli polynomials====
<langsyntaxhighlight Haskelllang="haskell">import Data.Ratio ((%), numerator, denominator)
import Data.List (intercalate, transpose)
import Data.Bifunctor (bimap)
Line 1,193:
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:
Implementation:
 
<langsyntaxhighlight Jlang="j">Bsecond=:verb define"0
+/,(<:*(_1^[)*!*(y^~1+[)%1+])"0/~i.1x+y
)
Line 1,218:
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:
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:
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:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 1,416:
 
'''Module''':
<langsyntaxhighlight lang="julia">module Faulhaber
 
function bernoulli(n::Integer)
Line 1,456:
end
 
end # module Faulhaber</langsyntaxhighlight>
 
'''Main''':
<syntaxhighlight lang ="julia">Faulhaber.formula.(1:10)</langsyntaxhighlight>
 
{{out}}
Line 1,475:
=={{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:
fun main(args: Array<String>) {
for (i in 0..9) faulhaber(i)
}</langsyntaxhighlight>
 
{{out}}
Line 1,611:
=={{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:
for i=0,9 do
faulhaber(i)
end</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 1,770:
 
=={{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:
 
=={{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:
[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:
=={{header|Modula-2}}==
{{trans|C#}}
<langsyntaxhighlight lang="modula2">MODULE Faulhaber;
FROM EXCEPTIONS IMPORT AllocateSource,ExceptionSource,GetMessage,RAISE;
FROM FormatString IMPORT FormatString;
Line 1,991:
END;
ReadChar
END Faulhaber.</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 2,006:
=={{header|Nim}}==
{{trans|Kotlin}}
<langsyntaxhighlight Nimlang="nim">import math, rationals
 
type
Line 2,079:
 
for n in 0..9:
echo n, ": ", faulhaber(n)</langsyntaxhighlight>
 
{{out}}
Line 2,101:
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:
{\\ Testing:
for(i=0,9, Faulhaber2(i))}
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 2,151:
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:
{\\ Testing:
for(i=0,9, Faulhaber1(i))}
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 2,180:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use 5.014;
use Math::Algebra::Symbols;
 
Line 2,222:
foreach my $i (0 .. 9) {
say "$i: ", faulhaber_s_formula($i);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,239:
=={{header|Phix}}==
{{trans|C#}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
Line 2,301:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,328:
 
 
<langsyntaxhighlight lang="python">from fractions import Fraction
 
def nextu(a):
Line 2,390:
 
for i, p in enumerate(sumpol(10)):
print(i, ":", polstr(p))</langsyntaxhighlight>
 
{{out}}
Line 2,408:
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,464:
(for ((p (in-range 0 (add1 9))))
(printf "f(~a) = ~a~%" p (expression->infix-string (faulhaber p))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,483:
(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,521:
for 0..9 -> $p {
say "f($p) = ", faulhaber_s_formula($p);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,538:
=={{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,625:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 2,640:
=={{header|Scala}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">import scala.math.Ordering.Implicits.infixOrderingOps
 
abstract class Frac extends Comparable[Frac] {
Line 2,810:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 2,824:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">const AnyNum = require('Math::AnyNum')
const Poly = require('Math::Polynomial')
 
Line 2,846:
for p in (^10) {
printf("%2d: %s\n", p, faulhaber_formula(p))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,863:
=={{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,025:
Next
End Sub
End Module</langsyntaxhighlight>
{{out}}
<pre>0 : n
Line 3,042:
{{libheader|Wren-math}}
{{libheader|Wren-rat}}
<langsyntaxhighlight lang="ecmascript">import "/math" for Int
import "/rat" for Rat
 
Line 3,094:
}
 
for (i in 0..9) faulhaber.call(i)</langsyntaxhighlight>
 
{{out}}
Line 3,113:
{{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,145:
}
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,162:
if(str[0]=="+") str[1,*]; // leave leading space
else String("-",str[2,*]);
}</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits