Bernoulli numbers: Difference between revisions

m
m (Corrected typo.)
 
(31 intermediate revisions by 17 users not shown)
Line 10:
 
:* &nbsp; show the Bernoulli numbers &nbsp; '''B'''<sub>0</sub> &nbsp; through &nbsp; '''B'''<sub>60</sub>.
:* &nbsp; suppress the output of values which are equal to zero. &nbsp; (Other than &nbsp; '''B'''<sub>1</sub>&nbsp;, all &nbsp; ''odd'' &nbsp; Bernoulli numbers have a value of zero.)
:* &nbsp; express the Bernoulli numbers as fractions &nbsp;(most are improper fractions).
:* &nbsp; the fractions should be reduced.
Line 27:
 
;See also
* Sequence [http[oeis://oeis.org/A027641 |A027641 Numerator of Bernoulli number B_n]] on The On-Line Encyclopedia of Integer Sequences.
* Sequence [http[oeis://oeis.org/A027642 |A027642 Denominator of Bernoulli number B_n]] on The On-Line Encyclopedia of Integer Sequences.
* Entry [http://mathworld.wolfram.com/BernoulliNumber.html Bernoulli number] on The Eric Weisstein's World of Mathematics (TM).
* Luschny's [http://luschny.de/math/zeta/The-Bernoulli-Manifesto.html The Bernoulli Manifesto] for a discussion on &nbsp; <big> '''B<sub>1</sub> &nbsp; = &nbsp; -&frac12;''' &nbsp; versus &nbsp; '''+&frac12;'''. </big>
<br><br>
 
=={{header|Ada}}==
Using a GMP thick binding available at http://www.codeforge.com/article/422541
 
<langsyntaxhighlight Adalang="ada">WITH GMP.Rationals, GMP.Integers, Ada.Text_IO, Ada.Strings.Fixed, Ada.Strings;
USE GMP.Rationals, GMP.Integers, Ada.Text_IO, Ada.Strings.Fixed, Ada.Strings;
 
Line 67 ⟶ 66:
END IF;
END LOOP;
END Main;</langsyntaxhighlight>
{{out}}
<pre>
Line 103 ⟶ 102:
B(60)=-1215233140483755572040304994079820246041491 / 56786730
</pre>
 
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses the LONG LONG INT mode of Algol 68G which allows large precision integers.
<langsyntaxhighlight lang="algol68">BEGIN
# Show Bernoulli numbers B0 to B60 as rational numbers #
 
Line 184 ⟶ 182:
OD
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 220 ⟶ 218:
B(60) -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|AppleScript}}==
To be able to handle numbers up to B(60) and beyond, this script represents the numbers with lists whose items are the digit values — which of course requires custom math routines.
<syntaxhighlight lang="applescript">on bernoullis(n) -- Return a list of "numerator / denominator" texts representing Bernoulli numbers B(0) to B(n).
set listMathScript to getListMathScript(10) -- Script object providing custom list math routines.
set output to {}
-- Akiyama–Tanigawa algorithm for the "second Bernoulli numbers".
-- List 'a' will contain {numerator, denominator} lists representing fractions.
-- The numerators and denominators will in turn be lists containing integers representing their (decimal) digits.
set a to {}
repeat with m from 0 to n
-- Append the structure for 1 / (m + 1) to the end of a.
set {numerator2, denominator2} to {{1}, listMathScript's intToList(m + 1)}
set a's end to result
repeat with j from m to 1 by -1
-- Retrieve the preceding numerator and denominator.
set {numerator1, denominator1} to a's item j
tell listMathScript
-- Get the two fractions' lowest common denominator and adjust the numerators accordingly.
set lcd to its lcm(denominator1, denominator2)
set numerator1 to its multiply(numerator1, its |div|(lcd, denominator1))
set numerator2 to its multiply(numerator2, its |div|(lcd, denominator2))
-- Subtract numerator2 from numerator1 and multiply the result by j.
-- Assign the results to numerator2 and denominator2 for the next iteration.
set numerator2 to its multiply(its subtract(numerator1, numerator2), its intToList(j))
set denominator2 to lcd
end tell
-- Also store them in a's slot j. No need to reduce them here.
set a's item j to {numerator2, denominator2}
end repeat
-- The fraction just stored in a's first slot is Bernoulli(m). Reduce it and append a text representation to the output.
tell listMathScript
set gcd to its hcf(numerator2, denominator2)
set numerator2 to its |div|(numerator2, gcd)
set denominator2 to its |div|(denominator2, gcd)
set end of output to its listToText(numerator2) & (" / " & its listToText(denominator2))
end tell
end repeat
return output
end bernoullis
 
on getListMathScript(base)
script
on multiply(lst1, lst2) -- Multiply lst1 by lst2.
set lst1Length to (count lst1)
set lst2Length to (count lst2)
set productLength to lst1Length + lst2Length - 1
set product to {}
repeat productLength times
set product's end to 0
end repeat
-- Long multiplication algorithm, updating product digits on the fly instead of summing rows at the end.
repeat with lst2Index from -1 to -lst2Length by -1
set lst2Digit to lst2's item lst2Index
if (lst2Digit is not 0) then
set carry to 0
set productIndex to lst2Index
repeat with lst1Index from lst1's length to 1 by -1
tell lst2Digit * (lst1's item lst1Index) + carry + (product's item productIndex)
set product's item productIndex to (it mod base)
set carry to (it div base)
end tell
set productIndex to productIndex - 1
end repeat
if (carry = 0) then
else if (productIndex < -productLength) then
set product's beginning to carry
else
set product's item productIndex to (product's item productIndex) + carry
end if
end if
end repeat
return product
end multiply
on subtract(lst1, lst2) -- Subtract lst2 from lst1.
set lst1Length to (count lst1)
set lst2Length to (count lst2)
-- Pad copies to equal lengths.
copy lst1 to lst1
repeat (lst2Length - lst1Length) times
set lst1's beginning to 0
end repeat
copy lst2 to lst2
repeat (lst1Length - lst2Length) times
set lst2's beginning to 0
end repeat
-- Is lst2's numeric value greater than lst1's?
set paddedLength to (count lst1)
repeat with i from 1 to paddedLength
set lst1Digit to lst1's item i
set lst2Digit to lst2's item i
set lst2Greater to (lst2Digit > lst1Digit)
if ((lst2Greater) or (lst1Digit > lst2Digit)) then exit repeat
end repeat
-- If so, set up to subtract lst1 from lst2 instead. We'll invert the result's sign at the end.
if (lst2Greater) then tell lst2
set lst2 to lst1
set lst1 to it
end tell
-- The subtraction at last!
set difference to {}
set borrow to 0
repeat with i from paddedLength to 1 by -1
tell (lst1's item i) + base - borrow - (lst2's item i)
set difference's beginning to (it mod base)
set borrow to 1 - (it div base)
end tell
end repeat
if (lst2Greater) then invert(difference)
return difference
end subtract
on |div|(lst1, lst2) -- List lst1 div lst2.
return divide(lst1, lst2)'s quotient
end |div|
on |mod|(lst1, lst2) -- List lst1 mod lst2.
return divide(lst1, lst2)'s remainder
end |mod|
on divide(lst1, lst2) -- Divide lst1 by lst2. Return a record containing separate lists for the quotient and remainder.
set dividend to trim(lst1)
set divisor to trim(lst2)
set dividendLength to (count dividend)
set divisorLength to (count divisor)
if (divisorLength > dividendLength) then return {quotient:{0}, remainder:dividend}
-- Note the dividend's and divisor's signs, but use absolute values in the division.
set dividendNegative to (dividend's beginning < 0)
if (dividendNegative) then invert(dividend)
set divisorNegative to (divisor's beginning < 0)
if (divisorNegative) then invert(divisor)
-- Long-division algorithm, but quotient digits are subtraction counts.
set quotient to {}
if (divisorLength > 1) then
set remainder to dividend's items 1 thru (divisorLength - 1)
else
set remainder to {}
end if
repeat with nextSlot from divisorLength to dividendLength
set remainder's end to dividend's item nextSlot
repeat with subtractionCount from 0 to base -- Only ever reaches base - 1.
set subtractionResult to trim(subtract(remainder, divisor))
if (subtractionResult's beginning < 0) then exit repeat
set remainder to subtractionResult
end repeat
set end of quotient to subtractionCount
end repeat
-- The quotient's negative if the input signs are different. Positive otherwise.
if (dividendNegative ≠ divisorNegative) then invert(quotient)
-- The remainder has the same sign as the dividend.
if (dividendNegative) then invert(remainder)
return {quotient:quotient, remainder:remainder}
end divide
on lcm(lst1, lst2) -- Lowest common multiple of lst1 and lst2.
return multiply(lst2, |div|(lst1, hcf(lst1, lst2)))
end lcm
on hcf(lst1, lst2) -- Highest common factor of lst1 and lst2.
set lst1 to trim(lst1)
set lst2 to trim(lst2)
repeat until (lst2 = {0})
set x to lst1
set lst1 to lst2
set lst2 to trim(|mod|(x, lst2))
end repeat
if (lst1's beginning < 0) then invert(lst1)
return lst1
end hcf
on invert(lst) -- Invert the sign of all lst's "digits".
repeat with thisDigit in lst
set thisDigit's contents to -thisDigit
end repeat
end invert
on trim(lst) -- Return a copy of lst with no leading zeros.
repeat with i from 1 to (count lst)
if (lst's item i is not 0) then exit repeat
end repeat
return lst's items i thru end
end trim
on intToList(n) -- Return a list of numbers representing n's digits.
set lst to {n mod base}
set n to n div base
repeat until (n = 0)
set beginning of lst to n mod base as integer
set n to n div base
end repeat
return lst
end intToList
on listToText(lst) -- Return the number represented by the input list as text.
-- This lazily assumes 2 <= base <= 10. :)
set lst to trim(lst)
if (lst's beginning < 0) then
invert(lst)
set lst's beginning to "-"
end if
return join(lst, "")
end listToText
end script
return result
end getListMathScript
 
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
 
on task()
set maxN to 60
set output to {""}
set padding to " = "
set bernoulliNumbers to bernoullis(maxN)
repeat with n from 0 to maxN
set bernie to bernoulliNumbers's item (n + 1)
if (bernie does not start with "0") then
set Bn to "B(" & n & ")"
set output's end to Bn & ¬
text ((count Bn) - 3) thru (50 - (offset of "/" in bernie)) of padding & ¬
bernie
end if
end repeat
return join(output, linefeed)
end task
 
task()</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">"
B(0) = 1 / 1
B(1) = 1 / 2
B(2) = 1 / 6
B(4) = -1 / 30
B(6) = 1 / 42
B(8) = -1 / 30
B(10) = 5 / 66
B(12) = -691 / 2730
B(14) = 7 / 6
B(16) = -3617 / 510
B(18) = 43867 / 798
B(20) = -174611 / 330
B(22) = 854513 / 138
B(24) = -236364091 / 2730
B(26) = 8553103 / 6
B(28) = -23749461029 / 870
B(30) = 8615841276005 / 14322
B(32) = -7709321041217 / 510
B(34) = 2577687858367 / 6
B(36) = -26315271553053477373 / 1919190
B(38) = 2929993913841559 / 6
B(40) = -261082718496449122051 / 13530
B(42) = 1520097643918070802691 / 1806
B(44) = -27833269579301024235023 / 690
B(46) = 596451111593912163277961 / 282
B(48) = -5609403368997817686249127547 / 46410
B(50) = 495057205241079648212477525 / 66
B(52) = -801165718135489957347924991853 / 1590
B(54) = 29149963634884862421418123812691 / 798
B(56) = -2479392929313226753685415739663229 / 870
B(58) = 84483613348880041862046775994036021 / 354
B(60) = -1215233140483755572040304994079820246041491 / 56786730"</syntaxhighlight>
=={{header|Bracmat}}==
<langsyntaxhighlight lang="bracmat"> ( BernoulliList
= B Bs answer indLn indexLen indexPadding
, n numberPadding p solPos solidusPos sp
Line 281 ⟶ 559:
& str$!answer
)
& BernoulliList$60;</langsyntaxhighlight>
<pre>B(0)= 1/1
B(1)= 1/2
Line 314 ⟶ 592:
B(58)= 84483613348880041862046775994036021/354
B(60)=-1215233140483755572040304994079820246041491/56786730</pre>
 
=={{header|C}}==
{{libheader|GMP}}
<syntaxhighlight lang="c">
<lang C>
#include <stdlib.h>
#include <gmp.h>
Line 369 ⟶ 646:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 405 ⟶ 682:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
 
=={{header|C sharp|C#}}==
 
Line 411 ⟶ 687:
{{libheader|Mpir.NET}}
Translation of the C implementation
<langsyntaxhighlight lang="csharp">
using Mpir.NET;
using System;
Line 465 ⟶ 741:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 505 ⟶ 781:
 
{{libheader|MathNet.Numerics}}
<langsyntaxhighlight lang="csharp">
using System;
using System.Console;
Line 557 ⟶ 833:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 597 ⟶ 873:
{{libheader|System.Numerics}}
Algo based on the example provided in the header of this RC page (the one from Wikipedia). <br/> Extra feature - one can override the default of 60 by supplying a suitable number on the command line. The column widths are not hard-coded, but will adapt to the widths of the items listed.
<langsyntaxhighlight lang="csharp">using System;
using System.Numerics;
using System.Collections.Generic;
Line 655 ⟶ 931:
}
}
</syntaxhighlight>
</lang>
{{out}}
Default (nothing entered on command line):
Line 767 ⟶ 1,043:
B(126) = 5556330281949274850616324408918951380525567307126747246796782304333594286400508981287241419934529638692081513802696639 / 4357878
</pre>
 
=={{header|C++}}==
{{Works with|C++11}}
{{libheader|boost}}
<langsyntaxhighlight lang="cpp">/**
* Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
* Apple LLVM version 9.1.0 (clang-902.0.39.1)
Line 806 ⟶ 1,081:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 842 ⟶ 1,117:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="clojure">
 
ns test-project-intellij.core
Line 872 ⟶ 1,146:
(println q ":" (format-ans ans)))
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 908 ⟶ 1,182:
60 : -1215233140483755572040304994079820246041491 / 56786730
</pre>
 
=={{header|Common Lisp}}==
An implementation of the simple algorithm.
Line 914 ⟶ 1,187:
Be advised that the pseudocode algorithm specifies (j * (a[j-1] - a[j])) in the inner loop; implementing that as-is gives the wrong value (1/2) where n = 1, whereas subtracting a[j]-a[j-1] yields the correct value (B[1]=-1/2). See [http://oeis.org/A027641 the numerator list].
 
<langsyntaxhighlight lang="lisp">(defun bernouilli (n)
(loop with a = (make-array (list (1+ n)))
for m from 0 to n do
Line 956 ⟶ 1,229:
n
(numerator r)
(denominator r)))))</langsyntaxhighlight>
 
{{out}}
Line 993 ⟶ 1,266:
B(60): -1215233140483755572040304994079820246041491/56786730
</pre>
 
=={{header|Crystal}}==
 
{{Trans|Ruby}}
 
<langsyntaxhighlight lang="ruby">require "big"
 
class Bernoulli
Line 1,025 ⟶ 1,297:
puts "B(%2i) = %*i/%i" % [i, max_width, v.numerator, v.denominator]
end
</syntaxhighlight>
</lang>
 
{{Trans|Python}}
Version 1: compute each number separately.
<langsyntaxhighlight lang="ruby">require "big"
 
def bernoulli(n)
Line 1,043 ⟶ 1,315:
width = b_nums.map{ |b| b.numerator.to_s.size }.max
b_nums.each_with_index { |b,i| puts "B(%2i) = %*i/%i" % [i, width, b.numerator, b.denominator] unless b.zero? }
</syntaxhighlight>
</lang>
 
 
{{Trans|Python}}
Version 2: create faster generator to compute array of numbers once.
<langsyntaxhighlight lang="ruby">require "big"
 
def bernoulli2(limit)
Line 1,063 ⟶ 1,335:
width = b_nums.map{ |b| b.numerator.to_s.size }.max
b_nums.each_with_index { |b,i| puts "B(%2i) = %*i/%i" % [i, width, b.numerator, b.denominator] unless b.zero? }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,099 ⟶ 1,371:
B(60) = -1215233140483755572040304994079820246041491/56786730
</pre>
 
=={{header|D}}==
This uses the D module from the Arithmetic/Rational task.
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.algorithm, std.conv, arithmetic_rational;
 
auto bernoulli(in uint n) pure nothrow /*@safe*/ {
Line 1,120 ⟶ 1,391:
foreach (immutable b; berns)
writefln("B(%2d) = %*d/%d", b[0], width, b[1].tupleof);
}</langsyntaxhighlight>
The output is exactly the same as the Python entry.
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| Velthuis.BigRationals}}
{{Trans|Go}}
Thanks Rudy Velthuis for the [https://github.com/rvelthuis/DelphiBigNumbers Velthuis.BigRationals] library.<br>
 
<syntaxhighlight lang="delphi">
program Bernoulli_numbers;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
Velthuis.BigRationals;
 
function b(n: Integer): BigRational;
begin
var a: TArray<BigRational>;
SetLength(a, n + 1);
for var m := 0 to High(a) do
begin
a[m] := BigRational.Create(1, m + 1);
for var j := m downto 1 do
begin
a[j - 1] := (a[j - 1] - a[j]) * j;
end;
end;
Result := a[0];
end;
 
begin
for var n := 0 to 60 do
begin
var bb := b(n);
if bb.Numerator.BitLength > 0 then
writeln(format('B(%2d) =%45s/%s', [n, bb.Numerator.ToString, bb.Denominator.ToString]));
end;
readln;
end.</syntaxhighlight>
=={{header|EchoLisp}}==
 
Line 1,128 ⟶ 1,437:
 
Only 'small' rationals are supported in EchoLisp, i.e numerator and demominator < 2^31. So, we create a class of 'large' rationals, supported by the bigint library, and then apply the magic formula.
<langsyntaxhighlight lang="lisp">
(lib 'bigint) ;; lerge numbers
(lib 'gloops) ;; classes
Line 1,153 ⟶ 1,462:
(define-method div (Rational Rational) (lambda (r q)
(normalize (Rational (* r.a q.b) (* r.b q.a)))))
</syntaxhighlight>
</lang>
{{Output}}
<langsyntaxhighlight lang="lisp">
;; Bernoulli numbers
;; http://rosettacode.org/wiki/Bernoulli_numbers
Line 1,203 ⟶ 1,512:
 
(B 1) → 1 / 2
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Bernoulli do
defmodule Rational do
import Kernel, except: [div: 2]
Line 1,260 ⟶ 1,568:
end
 
Bernoulli.task</langsyntaxhighlight>
 
{{out}}
Line 1,297 ⟶ 1,605:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
 
=={{header|F sharp|F#}}==
{{libheader|MathNet.Numerics.FSharp}}
<langsyntaxhighlight lang="fsharp">
open MathNet.Numerics
open System
Line 1,326 ⟶ 1,633:
printf ""
0
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,362 ⟶ 1,669:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
 
=={{header|Factor}}==
One could use the "bernoulli" word from the math.extras vocabulary as follows:
<syntaxhighlight lang="text">IN: scratchpad
[
0 1 1 "%2d : %d / %d\n" printf
Line 1,406 ⟶ 1,712:
58 : 84483613348880041862046775994036021 / 354
60 : -1215233140483755572040304994079820246041491 / 56786730
Running time: 0.00489444 seconds</langsyntaxhighlight>
Alternatively a method described by Brent and Harvey (2011) in "Fast computation of Bernoulli, Tangent and Secant numbers" https://arxiv.org/pdf/1108.0286.pdf is shown.
<syntaxhighlight lang="text">:: bernoulli-numbers ( n -- )
n 1 + 0 <array> :> tab
1 1 tab set-nth
Line 1,442 ⟶ 1,748:
"%2d : %d / %d\n" printf
] each
;</langsyntaxhighlight>
It gives the same result as the native implementation, but is slightly faster.
<syntaxhighlight lang="text">[ 30 bernoulli-numbers ] time
...
Running time: 0.004331652 seconds</langsyntaxhighlight>
=={{header|Fermat}}==
 
<syntaxhighlight lang="fermat">Func Bern(m) = Sigma<k=0,m>[Sigma<v=0,k>[(-1)^v*Bin(k,v)*(v+1)^m/(k+1)]].;
for i=0, 60 do b:=Bern(i); if b<>0 then !!(i,b) fi od;</syntaxhighlight>
{{out}}<pre>
0 1
1 1 / 2
2 1 / 6
4 -1 / 30
6 1 / 42
8 -1 / 30
10 5 / 66
12 -691 / 2730
14 7 / 6
16 -3617 / 510
18 43867 / 798
20 -174611 / 330
22 854513 / 138
24 -236364091 / 2730
26 8553103 / 6
28 -23749461029 / 870
30 8615841276005 / 14322
32 -7709321041217 / 510
34 2577687858367 / 6
36 -26315271553053477373 / 1919190
38 2929993913841559 / 6
40 -261082718496449122051 / 13530
42 1520097643918070802691 / 1806
44 -27833269579301024235023 / 690
46 596451111593912163277961 / 282
48 -5609403368997817686249127547 / 46410
50 495057205241079648212477525 / 66
52 -801165718135489957347924991853 / 1590
54 29149963634884862421418123812691 / 798
56 -2479392929313226753685415739663229 / 870
58 84483613348880041862046775994036021 / 354
60 -1215233140483755572040304994079820246041491 / 56786730</pre>
=={{header|FreeBASIC}}==
{{libheader|GMP}}
<langsyntaxhighlight lang="freebasic">' version 08-10-2016
' compile with: fbc -s console
' uses gmp
Line 1,503 ⟶ 1,844:
Print :Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>B( 0) = 1/1
Line 1,537 ⟶ 1,878:
B(58) = 84483613348880041862046775994036021/354
B(60) = -1215233140483755572040304994079820246041491/56786730</pre>
=={{header|Frink}}==
<syntaxhighlight lang="frink">BernoulliNumber[n] :=
{
a = new array
for m = 0 to n
{
a@m = 1/(m+1)
for j = m to 1 step -1
a@(j-1) = j * (a@(j-1) - a@j)
}
 
return a@0
}
 
result = new array
for n=0 to 60
{
b = BernoulliNumber[n]
if b != 0
{
[num,den] = numeratorDenominator[b]
result.push[[n, num, "/", den]]
}
}
 
println[formatTable[result, "right"]]</syntaxhighlight>
 
{{out}}
<pre>
0 1 / 1
1 1 / 2
2 1 / 6
4 -1 / 30
6 1 / 42
8 -1 / 30
10 5 / 66
12 -691 / 2730
14 7 / 6
16 -3617 / 510
18 43867 / 798
20 -174611 / 330
22 854513 / 138
24 -236364091 / 2730
26 8553103 / 6
28 -23749461029 / 870
30 8615841276005 / 14322
32 -7709321041217 / 510
34 2577687858367 / 6
36 -26315271553053477373 / 1919190
38 2929993913841559 / 6
40 -261082718496449122051 / 13530
42 1520097643918070802691 / 1806
44 -27833269579301024235023 / 690
46 596451111593912163277961 / 282
48 -5609403368997817686249127547 / 46410
50 495057205241079648212477525 / 66
52 -801165718135489957347924991853 / 1590
54 29149963634884862421418123812691 / 798
56 -2479392929313226753685415739663229 / 870
58 84483613348880041862046775994036021 / 354
60 -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|FunL}}==
FunL has pre-defined function <code>B</code> in module <code>integers</code>, which is defined as:
<langsyntaxhighlight lang="funl">import integers.choose
 
def B( n ) = sum( 1/(k + 1)*sum((if 2|r then 1 else -1)*choose(k, r)*(r^n) | r <- 0..k) | k <- 0..n )
 
for i <- 0..60 if i == 1 or 2|i
printf( "B(%2d) = %s\n", i, B(i) )</langsyntaxhighlight>
 
{{out}}
Line 1,582 ⟶ 1,984:
B(60) = -1215233140483755572040304994079820246041491/56786730
</pre>
 
=={{header|Fōrmulæ}}==
 
In [{{FormulaeEntry|page=https://wiki.formulae.org/?script=examples/Bernoulli_numbers this] page you can see the solution of this task.}}
 
'''Solution.''' The following function reduces to the n-th Bernoulli number. It is a replica of the Akiyama–Tanigawa algorithm.
 
[[File:Fōrmulæ - Bernoulli numbers 01.png]]
 
'''Test case.''' Showing the Bernoulli numbers B<sub>0</sub> to B<sub>60</sub>
 
[[File:Fōrmulæ - Bernoulli numbers 02.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æ - Bernoulli numbers 03.png]]
The option to show Fōrmulæ programs and their results is showing images. Unfortunately images cannot be uploaded in Rosetta Code.
 
=={{header|GAP}}==
 
<langsyntaxhighlight lang="gap">for a in Filtered(List([0 .. 60], n -> [n, Bernoulli(n)]), x -> x[2] <> 0) do
Print(a, "\n");
od;
Line 1,628 ⟶ 2,035:
[ 56, -2479392929313226753685415739663229/870 ]
[ 58, 84483613348880041862046775994036021/354 ]
[ 60, -1215233140483755572040304994079820246041491/56786730 ]</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,657 ⟶ 2,063:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,693 ⟶ 2,099:
B(60) = -1215233140483755572040304994079820246041491/56786730
</pre>
 
=={{header|Haskell}}==
====Task algorithm====
Line 1,699 ⟶ 2,104:
The implementation of the algorithm is in the function bernoullis. The rest is for printing the results.
 
<langsyntaxhighlight Haskelllang="haskell">import Data.Ratio
import System.Environment
 
Line 1,721 ⟶ 2,126:
berno i = 1 % (i + 1)
ulli _ [_] = []
ulli i (x:y:xs) = (i % 1) * (x - y) : ulli (i + 1) (y : xs)</langsyntaxhighlight>
{{Out}}
<pre>B(0) = 1/1
Line 1,757 ⟶ 2,162:
 
====Derivation from Faulhaber's triangle====
<syntaxhighlight lang ="haskell">import Data.Ratio (Ratio, numerator, denominator,Bool (%)bool)
import Data.BoolRatio (boolRatio, denominator, numerator, (%))
 
-------------------- BERNOULLI NUMBERS -------------------
 
bernouillis :: Integer -> [Rational]
bernouillis =
bernouillis = fmap head . tail . scanl faulhaber [] . enumFromTo 0
fmap head
. tail
. scanl faulhaber []
. enumFromTo 0
 
faulhaber :: [Ratio Integer] -> Integer -> [Ratio Integer]
faulhaber rs n = (:) =<< (-) 1 . sum $ zipWith ((*) . (n %)) [2 ..] rs
(:) =<< (-) 1 . sum $
zipWith ((*) . (n %)) [2 ..] rs
 
-- TEST -------------------------- TEST -------------------------
main :: IO ()
main = do
let xs = bernouillis 60
w = length ($ show (numerator (last xs)))
putStrLn $
fTable
Line 1,779 ⟶ 2,192:
(filter ((0 /=) . snd) $ zip [0 ..] xs)
 
-- FORMATTING ----------------------- FORMATTING ----------------------
fTable ::
fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String
String ->
(a -> String) ->
(b -> String) ->
(a -> b) ->
[a] ->
String
fTable s xShow fxShow f xs =
let w = maximum (length . xShow <$> xs)
in unlines $
s :
s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs
fmap
( ((<>) . rjust w ' ' . xShow)
<*> ((" -> " <>) . fxShow . f)
)
xs
 
showRatio :: Int -> Rational -> String
showRatio w r =
let d = denominator r
in rjust w ' ' ($ show (numerator r)) ++ bool [] (" / " ++ show d) (1 /= d)
<> bool [] (" / " <> show d) (1 /= d)
 
rjust :: Int -> a -> [a] -> [a]
rjust n c = drop . length <*> (replicate n c ++<>)</langsyntaxhighlight>
{{Out}}
<pre>Bernouillis from Faulhaber triangle:
Line 1,828 ⟶ 2,253:
58 -> 84483613348880041862046775994036021 / 354
60 -> -1215233140483755572040304994079820246041491 / 56786730</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
 
The following works in both languages:
<langsyntaxhighlight lang="unicon">link "rational"
 
procedure main(args)
Line 1,851 ⟶ 2,275:
procedure align(r,n)
return repl(" ",n-find("/",r))||r
end</langsyntaxhighlight>
 
Sample run:
Line 1,890 ⟶ 2,314:
->
</pre>
 
=={{header|J}}==
 
'''Implementation:'''
 
See [https[j://code.jsoftware.com/wiki/Essays/Bernoulli_Numbers |Bernoulli Numbers Essay]] on the J wiki.
<langsyntaxhighlight lang="j">B=: {.&1 %. (i. ! ])@>:@i.@x:</langsyntaxhighlight>
 
'''Task:'''
 
<langsyntaxhighlight lang="j"> 'B' ,. rplc&'r/_-'"1": (#~ 0 ~: {:"1)(i. ,. B) 61
B 0 1
B 1 -1/2
Line 1,932 ⟶ 2,355:
B56 -2479392929313226753685415739663229/870
B58 84483613348880041862046775994036021/354
B60 -1215233140483755572040304994079820246041491/56786730</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import org.apache.commons.math3.fraction.BigFraction;
 
public class BernoulliNumbers {
Line 1,956 ⟶ 2,378:
return A[0];
}
}</langsyntaxhighlight>
<pre>B(0 ) = 1
B(1 ) = 1 / 2
Line 1,989 ⟶ 2,411:
B(58) = 84483613348880041862046775994036021 / 354
B(60) = -1215233140483755572040304994079820246041491 / 56786730</pre>
 
=={{header|jq}}==
{{works with|jq|1.4}}
Line 1,999 ⟶ 2,420:
 
'''BigInt Stubs''':
<langsyntaxhighlight lang="jq"># def negate:
# def lessOrEqual(x; y): # x <= y
# def long_add(x;y): # x+y
Line 2,037 ⟶ 2,458:
 
def long_mod(x;y):
((x|tonumber) % (y|tonumber)) | tostring;</langsyntaxhighlight>
 
'''Fractions''':<langsyntaxhighlight lang="jq">
# A fraction is represented by [numerator, denominator] in reduced form, with the sign on top
 
Line 2,093 ⟶ 2,514:
| if $a == $b then ["0", "1"]
else add($a; [ ($b[0]|negate), $b[1] ] )
end ; </langsyntaxhighlight>
 
'''Bernoulli Numbers''':
<langsyntaxhighlight lang="jq"># Using the algorithm in the task description:
def bernoulli(n):
reduce range(0; n+1) as $m
Line 2,105 ⟶ 2,526:
.[$j-1] = multiply( [($j|tostring), "1"]; minus( .[$j-1] ; .[$j]) ) ))
| .[0] # (which is Bn)
;</langsyntaxhighlight>
 
'''The task''':
<langsyntaxhighlight lang="jq">range(0;61)
| if . % 2 == 0 or . == 1 then "\(.): \(bernoulli(.) )" else empty end</langsyntaxhighlight>
{{out}}
The following output was obtained using the previously mentioned BigInt library.
<langsyntaxhighlight lang="sh">$ jq -n -r -f Bernoulli.jq
0: ["1","1"]
1: ["1","2"]
Line 2,144 ⟶ 2,565:
56: ["-2479392929313226753685415739663229","870"]
58: ["84483613348880041862046775994036021","354"]
60: ["-1215233140483755572040304994079820246041491","56786730"]</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight Julialang="julia">function bernoulli(n)
A = Vector{Rational{BigInt}}(undef, n + 1)
for m = 0 : n
Line 2,192 ⟶ 2,612:
for (n, b) in enumerate(BernoulliList(60))
isodd(numerator(b)) && println("B($(n-1)) = $b")
end </langsyntaxhighlight>
 
Produces virtually the same output as the Python version.
 
=={{header|Kotlin}}==
{{trans|Java}}
{{works with|Commons Math|3.3.5}}
 
<langsyntaxhighlight lang="scala">import org.apache.commons.math3.fraction.BigFraction
 
object Bernoulli {
Line 2,221 ⟶ 2,640:
if (n % 2 == 0 || n == 1)
System.out.printf("B(%-2d) = %-1s%n", n, Bernoulli(n))
}</langsyntaxhighlight>
{{out}}
Produces virtually the same output as the Java version.
 
=={{header|Lua}}==
LuaJIT version with FFI and GMP library
Line 2,230 ⟶ 2,648:
{{libheader|luagmp}}
{{works with|LuaJIT|2.0-2.1}}
<langsyntaxhighlight lang="lua">#!/usr/bin/env luajit
local gmp = require 'gmp' ('libgmp')
local ffi = require'ffi'
Line 2,274 ⟶ 2,692:
gmp.z_clears(n,d)
gmp.q_clear(rop)
end</langsyntaxhighlight>
{{out}}
<pre>> time ./bernoulli_gmp.lua
Line 2,311 ⟶ 2,729:
./bernoulli_gmp.lua 0,02s user 0,00s system 97% cpu 0,022 total</pre>
Time compare: Python 0.591 sec, C 0.023 sec, Lua 0.022-0.025
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">print(select(n->n[2]<>0,[seq([n,bernoulli(n,1)],n=0..60)]));</langsyntaxhighlight>
{{out}}
<pre>[[0, 1], [1, 1/2], [2, 1/6], [4, -1/30], [6, 1/42], [8, -1/30], [10, 5/66], [12, -691/2730], [14, 7/6], [16, -3617/510], [18, 43867/798], [20, -174611/330], [22, 854513/138], [24, -236364091/2730], [26, 8553103/6], [28, -23749461029/870], [30, 8615841276005/14322], [32, -7709321041217/510], [34, 2577687858367/6], [36, -26315271553053477373/1919190], [38, 2929993913841559/6], [40, -261082718496449122051/13530], [42, 1520097643918070802691/1806], [44, -27833269579301024235023/690], [46, 596451111593912163277961/282], [48, -5609403368997817686249127547/46410], [50, 495057205241079648212477525/66], [52, -801165718135489957347924991853/1590], [54, 29149963634884862421418123812691/798], [56, -2479392929313226753685415739663229/870], [58, 84483613348880041862046775994036021/354], [60, -1215233140483755572040304994079820246041491/56786730]]</pre>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Mathematica has no native way for starting an array at index 0. I therefore had to build the array from 1 to n+1 instead of from 0 to n, adjusting the formula accordingly.
<langsyntaxhighlight Mathematicalang="mathematica">bernoulli[n_] := Module[{a = ConstantArray[0, n + 2]},
Do[
a[[m]] = 1/m;
Line 2,329 ⟶ 2,745:
, {m, 1, n + 1}];
]
bernoulli[60]</langsyntaxhighlight>
{{out}}
<pre>{0,1}
Line 2,367 ⟶ 2,783:
(Note from task's author: nobody is forced to use any specific algorithm, the one shown is just a suggestion.)
 
<langsyntaxhighlight Mathematicalang="mathematica">Table[{i, BernoulliB[i]}, {i, 0, 60}];
Select[%, #[[2]] != 0 &] // TableForm</langsyntaxhighlight>
{{out}}
<pre>0 1
Line 2,402 ⟶ 2,818:
58 84483613348880041862046775994036021/354
60 -(1215233140483755572040304994079820246041491/56786730)</pre>
 
=={{header|Maxima}}==
Using built-in function bern
<syntaxhighlight lang="maxima">
block(makelist([sconcat("B","(",i,")","="),bern(i)],i,0,60),
sublist(%%,lambda([x],x[2]#0)),
table_form(%%))
</syntaxhighlight>
{{out}}
<pre>
matrix(
["B(0)=", 1],
["B(1)=", -1/2],
["B(2)=", 1/6],
["B(4)=", -1/30],
["B(6)=", 1/42],
["B(8)=", -1/30],
["B(10)=", 5/66],
["B(12)=", -691/2730],
["B(14)=", 7/6],
["B(16)=", -3617/510],
["B(18)=", 43867/798],
["B(20)=", -174611/330],
["B(22)=", 854513/138],
["B(24)=", -236364091/2730],
["B(26)=", 8553103/6],
["B(28)=", -23749461029/870],
["B(30)=", 8615841276005/14322],
["B(32)=", -7709321041217/510],
["B(34)=", 2577687858367/6],
["B(36)=", -26315271553053477373/1919190],
["B(38)=", 2929993913841559/6],
["B(40)=", -261082718496449122051/13530],
["B(42)=", 1520097643918070802691/1806],
["B(44)=", -27833269579301024235023/690],
["B(46)=", 596451111593912163277961/282],
["B(48)=", -5609403368997817686249127547/46410],
["B(50)=", 495057205241079648212477525/66],
["B(52)=", -801165718135489957347924991853/1590],
["B(54)=", 29149963634884862421418123812691/798],
["B(56)=", -2479392929313226753685415739663229/870],
["B(58)=", 84483613348880041862046775994036021/354],
["B(60)=", -1215233140483755572040304994079820246041491/56786730]
)
</pre>
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import bignum
import strformat
 
Line 2,418 ⟶ 2,879:
a[m] = newRat(1, m + 1)
for j in countdown(m, 1):
a[j-1] = j * (a[j-1] - a[j-1])
result = a[0]
 
Line 2,445 ⟶ 2,906:
for (n, b) in values:
let s = fmt"{($b.num).alignString(maxLen, '>')} / {b.denom}"
echo fmt"{n:2}: {s}"</langsyntaxhighlight>
 
{{out}}
<pre> 0: 1 / 1
1: -1 / 2
2: 1 / 6
4: -1 / 30
Line 2,480 ⟶ 2,941:
58: 84483613348880041862046775994036021 / 354
60: -1215233140483755572040304994079820246041491 / 56786730</pre>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">for(n=0,60,t=bernfrac(n);if(t,print(n" "t)))</langsyntaxhighlight>
{{out}}
<pre>0 1
Line 2,516 ⟶ 2,976:
58 84483613348880041862046775994036021/354
60 -1215233140483755572040304994079820246041491/56786730</pre>
 
=={{header|Pascal|FreePascal}}==
{{libheader|BigDecimalMath}}
Tested with fpc 3.0.4
<syntaxhighlight lang="pascal">
<lang Pascal>
(* Taken from the 'Ada 99' project, https://marquisdegeek.com/code_ada99 *)
Line 2,643 ⟶ 3,102:
end;
end.
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,681 ⟶ 3,140:
B(60) : -1215233140483755572040304994079820246041491 / 56786730
</pre>
 
=={{header|Perl}}==
The only thing in the suggested algorithm which depends on N is the number of times through the inner block. This means that all but the last iteration through the loop produce the exact same values of A.
Line 2,687 ⟶ 3,145:
Instead of doing the same calculations over and over again, I retain the A array until the final Bernoulli number is produced.
 
<langsyntaxhighlight lang="perl">#!perl
use strict;
use warnings;
Line 2,711 ⟶ 3,169:
 
bernoulli_print();
</syntaxhighlight>
</lang>
The output is exactly the same as the Python entry.
 
We can also use modules for faster results. E.g.
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw/bernfrac/;
 
for my $n (0 .. 60) {
my($num,$den) = bernfrac($n);
printf "B(%2d) = %44s/%s\n", $n, $num, $den if $num != 0;
}</langsyntaxhighlight>
with identical output. Or:
<langsyntaxhighlight lang="perl">use Math::Pari qw/bernfrac/;
 
for my $n (0 .. 60) {
my($num,$den) = split "/", bernfrac($n);
printf("B(%2d) = %44s/%s\n", $n, $num, $den||1) if $num != 0;
}</langsyntaxhighlight>
with the difference being that Pari chooses <math>B_1</math> = -&frac12;.
 
=={{header|Phix}}==
{{libheader|Phix/mpfr}}
{{trans|C}}
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>include builtins/mpfr.e
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
procedure bernoulli(mpq rop, integer n)
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">/</span><span style="color: #004080;">mpfr</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
sequence a = mpq_init(n+1)
<span style="color: #008080;">procedure</span> <span style="color: #000000;">bernoulli</span><span style="color: #0000FF;">(</span><span style="color: #004080;">mpq</span> <span style="color: #000000;">rop</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=1 to n+1 do
<span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpq_inits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
mpq_set_si(a[m], 1, m)
<span style="color: #008080;">for</span> <span style="color: #000000;">m</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: #0000FF;">+</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
for j=m-1 to 1 by -1 do
<span style="color: #7060A8;">mpq_set_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</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> <span style="color: #000000;">m</span><span style="color: #0000FF;">)</span>
mpq_sub(a[j], 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: #0000FF;">-</span><span style="color: #000000;">1</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>
mpq_set_si(rop, j, 1)
<span style="color: #7060A8;">mpq_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;">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>
mpq_mul(a[j], a[j], rop)
<span style="color: #7060A8;">mpq_set_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rop</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>
end for
<span style="color: #7060A8;">mpq_mul</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;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">],</span> <span style="color: #000000;">rop</span><span style="color: #0000FF;">)</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
mpq_set(rop, a[1])
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
a = mpq_free(a)
<span style="color: #7060A8;">mpq_set</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rop</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>
end procedure
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpq_free</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
mpq rop = mpq_init()
mpz n = mpz_init(),
<span style="color: #004080;">mpq</span> <span style="color: #000000;">rop</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpq_init</span><span style="color: #0000FF;">()</span>
d = mpz_init()
<span style="color: #004080;">mpz</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">(),</span>
for i=0 to 60 do
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_init</span><span style="color: #0000FF;">()</span>
bernoulli(rop, 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;">60</span> <span style="color: #008080;">do</span>
if mpq_cmp_si(rop, 0, 1) then
<span style="color: #000000;">bernoulli</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rop</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
mpq_get_num(n, rop)
<span style="color: #008080;">if</span> <span style="color: #7060A8;">mpq_cmp_si</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rop</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
mpq_get_den(d, rop)
<span style="color: #7060A8;">mpq_get_num</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">rop</span><span style="color: #0000FF;">)</span>
string ns = mpfr_sprintf("%44Zd",n),
<span style="color: #7060A8;">mpq_get_den</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">rop</span><span style="color: #0000FF;">)</span>
ds = mpfr_sprintf("%Zd",d)
<span style="color: #004080;">string</span> <span style="color: #000000;">ns</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">),</span>
printf(1,"B(%2d) = %s / %s\n", {i,ns,ds})
<span style="color: #000000;">ds</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_get_str</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
end if
<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;">"B(%2d) = %44s / %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ns</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ds</span><span style="color: #0000FF;">})</span>
end for
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
{n,d} = mpz_free({n,d})
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
rop = mpq_free(rop)</lang>
<span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_free</span><span style="color: #0000FF;">({</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">rop</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpq_free</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rop</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,799 ⟶ 3,259:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
 
=={{header|PicoLisp}}==
Brute force and method by Srinivasa Ramanujan.
<langsyntaxhighlight PicoLisplang="picolisp">(load "@lib/frac.l")
 
(de fact (N)
Line 2,875 ⟶ 3,334:
(test (berno N) (berno-brute N)) )
 
(bye)</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">Bern: procedure options (main); /* 4 July 2014 */
declare i fixed binary;
declare B complex fixed (31);
Line 2,910 ⟶ 3,368:
(3 A, column(10), F(32), 2 A);
end;
end Bern;</langsyntaxhighlight>
The above uses GCD (see Rosetta Code) extended for 31-digit working.
 
Line 2,936 ⟶ 3,394:
B(36)= -26315271553053477373/1919190
</pre>
 
=={{header|Python}}==
===Python: Using task algorithm===
<langsyntaxhighlight lang="python">from fractions import Fraction as Fr
 
def bernoulli(n):
Line 2,953 ⟶ 3,410:
width = max(len(str(b.numerator)) for i,b in bn)
for i,b in bn:
print('B(%2i) = %*i/%i' % (i, width, b.numerator, b.denominator))</langsyntaxhighlight>
 
{{out}}
Line 2,991 ⟶ 3,448:
===Python: Optimised task algorithm===
Using the optimization mentioned in the Perl entry to reduce intermediate calculations we create and use the generator bernoulli2():
<langsyntaxhighlight lang="python">def bernoulli2():
A, m = [], 0
while True:
Line 3,004 ⟶ 3,461:
width = max(len(str(b.numerator)) for i,b in bn2)
for i,b in bn2:
print('B(%2i) = %*i/%i' % (i, width, b.numerator, b.denominator))</langsyntaxhighlight>
 
Output is exactly the same as before.
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> $ "bigrat.qky" loadfile
[ 1+
' [ [] ] over of swap
times
[ i^ 1+ n->v 1/v
join swap i^ poke
i^ times
[ dup i 1+ peek do
dip over swap i peek do
v- i 1+ n->v v*
join swap i poke ] ]
1 split drop do ] is bernoulli ( n --> n/d )
 
61 times
[ i^ bernoulli
2dup v0= iff
2drop
else
[ i^ 10 < if sp
i^ echo sp
vulgar$
char / over find
44 swap - times sp
echo$ cr ] ]</syntaxhighlight>
 
{{out}}
 
<pre> 0 1/1
1 -1/2
2 1/6
4 -1/30
6 1/42
8 -1/30
10 5/66
12 -691/2730
14 7/6
16 -3617/510
18 43867/798
20 -174611/330
22 854513/138
24 -236364091/2730
26 8553103/6
28 -23749461029/870
30 8615841276005/14322
32 -7709321041217/510
34 2577687858367/6
36 -26315271553053477373/1919190
38 2929993913841559/6
40 -261082718496449122051/13530
42 1520097643918070802691/1806
44 -27833269579301024235023/690
46 596451111593912163277961/282
48 -5609403368997817686249127547/46410
50 495057205241079648212477525/66
52 -801165718135489957347924991853/1590
54 29149963634884862421418123812691/798
56 -2479392929313226753685415739663229/870
58 84483613348880041862046775994036021/354
60 -1215233140483755572040304994079820246041491/56786730
</pre>
=={{header|R}}==
{{incorrect|rsplus|This example is incorrect: It is not executable and if made executable (with 'library(gmp)') it returns completely different and wrong results -- not the ones shown here. The R code needs complete rewrite and the 'pracma' library will not be of any help.}}
<lang rsplus>
 
<syntaxhighlight lang="rsplus">
 
library(pracma)
Line 3,019 ⟶ 3,540:
cat("B(",idx,") = ",n,"/",d,"\n", sep = "")
}
</langsyntaxhighlight>
{{out}}
<pre>
Line 3,055 ⟶ 3,576:
B(60) = -1215233140483755572040304994079820246041491/56786730
</pre>
 
=={{header|Racket}}==
 
Line 3,062 ⟶ 3,582:
use the same emmitter... it's just a matter of how long to wait for the emission.
 
<syntaxhighlight lang="text">#lang racket
;; For: http://rosettacode.org/wiki/Bernoulli_numbers
 
Line 3,145 ⟶ 3,665:
(list 1/1 (app abs 1/2) 1/6 -1/30 1/42 -1/30 _ ...))
; timing only ...
(void (time (bernoulli_0..n bernoulli.3 100))))</langsyntaxhighlight>
 
{{out}}
Line 3,180 ⟶ 3,700:
B(58) = 84483613348880041862046775994036021/354
B(60) = -1215233140483755572040304994079820246041491/56786730</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
Line 3,188 ⟶ 3,707:
First, a straighforward implementation of the naïve algorithm in the task description.
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" perl6line>sub bernoulli($n) {
my @a;
for 0..$n -> $m {
Line 3,204 ⟶ 3,723:
my $form = "B(%2d) = \%{$width}d/%d\n";
 
printf $form, .key, .value.nude for @bpairs;</langsyntaxhighlight>
{{out}}
<pre>B( 0) = 1/1
Line 3,244 ⟶ 3,763:
 
{{works with|Rakudo|2015.12}}
<syntaxhighlight lang="raku" perl6line>constant bernoulli = gather {
my @a;
for 0..* -> $m {
Line 3,261 ⟶ 3,780:
my $form = "B(%d)\t= \%{$width}d/%d\n";
 
printf $form, .key, .value.nude for @bpairs;</langsyntaxhighlight>
{{out}}
<pre>B(0) = 1/1
Line 3,321 ⟶ 3,840:
{{works with|Rakudo|2016.12}}
 
<syntaxhighlight lang="raku" perl6line>sub infix:<bop>(\prev, \this) {
this.key => this.key * (this.value - prev.value)
}
Line 3,343 ⟶ 3,862:
my $form = "B(%d)\t= \%{$width}d/%d\n";
printf $form, .key, .value.nude for @bpairs;</langsyntaxhighlight>
 
Same output as memoization example
Line 3,353 ⟶ 3,872:
<br>
:::::::::::: where &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <big><big> <math> \binom kr</math> </big></big> &nbsp; &nbsp; &nbsp; is a binomial coefficient. <br>
<langsyntaxhighlight lang="rexx">/*REXX program calculates N number of Bernoulli numbers expressed as vulgar fractions. */
parse arg N .; if N=='' | N=="," then N= 60 /*Not specified? Then use the default.*/
numeric digits max(9, n*2) /*increase the decimal digits if needed*/
w= max(length(N), 4); Nw= N + w + N % 4 /*used for aligning (output) fractions.*/
say 'B(n)' center("Bernoulli numbernumbers expressed as avulgar fractionfractions", max(78-w, Nw)) /*title.*/)
say copies('─',w) copies("─", max(78-w,Nw+2*w)) /*display 2nd line of title, separators*/
!.= 0.; do #=0 to N /*process the numbers from 0 ──► N. */
b= bern(#); if b==0 then iterate /*calculate Bernoulli number, skip if 0*/
indent= max(0, nW - pos('/', b) ) /*calculate the alignment (indentation)*/
say right(#, w) left('', indent) b /*display the indented Bernoulli number*/
end /*#*/ /* [↑] align the Bernoulli fractions. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
bern: parse arg x; if x==0 then return '1/1' /*handle the special case of zero. */
Line 3,377 ⟶ 3,896:
$lcm= LCM(sd, ad) /*use Least Common Denominator function*/
sn= $lcm % sd * sn; sd= $lcm /*calculate the current numerator. */
an= $lcm % ad * an; ad= $lcm /* " " next " */
sn= sn + an /* " " current " */
end /*k*/ /* [↑] calculate the SN/SD sequence.*/
Line 3,390 ⟶ 3,909:
/*──────────────────────────────────────────────────────────────────────────────────────*/
comb: procedure expose !.; parse arg x,y; if x==y then return 1
if !.cC.x.y\==0. then return !.cC.x.y /*combination computed before?*/
if x-y < y then y= x-y /*x-y < y? Then use a new Y.*/
z= perm(x, y); do j=2 for y-1; z= z % j
end /*j*/
!.cC.x.y= z; return z /*assign memoization & return.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
GCD: procedure; parse arg x,y; x= abs(x)
do until y==0; parse value x//y y with y x; end; return x
/*──────────────────────────────────────────────────────────────────────────────────────*/
LCM: procedure; parse arg x,y /*X=ABS(X); Y=ABS(Y) ¬not needed for Bernoulli #s.*/
/*IF Y==0 THEN RETURN 0 " " " " " */
$= x * y $= x * y /*calculate part of the LCM here. */
do until y==0; parse value x//y y with y x
end /*until*/ end /*until*/ /* [↑] this is a short & fast GCD*/
return $ % x return $ % x /*divide the pre─calculated value.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
perm: procedure expose !.; parse arg x,y; if !.pP.x.y \== 0. then return !.pP.x.y
z= 1; do j=x-y+1 to x; z= z*j; end; !.pP.x.y= z; return z</syntaxhighlight>
</lang>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
B(n) Bernoulli numbernumbers expressed as avulgar fractionfractions
──── ───────────────────────────────────────────────────────────────────────────────────────
0 1/1
Line 3,446 ⟶ 3,964:
60 -1215233140483755572040304994079820246041491/56786730
</pre>
 
Output notes: &nbsp; This version of REXX can compute and display all values up to &nbsp; '''B<sub>110</sub>''' &nbsp; in sub─second.
<br><br>
=={{header|RPL}}==
Fractions such as a/b are here handled through the complex number data structure <code>(a,b)</code>.
2 local words support the algorithm suggested by the task: <code>FracSub</code> substracts 2 fractions and <code>FracSimp</code> make a fraction irreducible
Unfortunately, floating-point precision prevents from going beyond B22.
{{works with|Halcyon Calc|4.2.7}}
{| class="wikitable"
! RPL code
! Comment
|-
|
≪ DUP2 IM * ROT IM ROT RE * -
≫ '<span style="color:blue">FracSub</span>' STO
≪ DUP C→R ABS SWAP ABS DUP2 < ≪ SWAP ≫ IFT
'''WHILE''' DUP '''REPEAT''' SWAP OVER MOD '''END'''
DROP /
≫ '<span style="color:blue">FracSimp</span>' STO
{ } 1 ROT 1 + '''FOR''' m
1 m R→C +
'''IF''' m 2 ≥ '''THEN''' m 2 '''FOR''' j
DUP j 1 - GET OVER j GET <span style="color:blue">FracSub</span>
C→R SWAP j 1 - * SWAP R→C
<span style="color:blue">FracSimp</span> j 1 - SWAP PUT
-1 '''STEP END'''
'''NEXT''' 1 GET DUP RE SWAP 0 '''IFTE'''
≫ '<span style="color:blue">BRNOU</span>' STO
|
''( (a,b) (c,d) -- (e,f) )'' with e/f = a/b - c/d
''( (a,b) -- (c,d) )'' with c/d simplified fraction of a/b
get GCD of a and b
divide (a,b) by GCD
''( n -- (a,b) )'' with a/b = B(n)
For m from 1 to n+1 do
A[m] ← 1/m
for j from m to 2 do
(A[j-1] - A[j])
. * (j-1)
A[j-1] ←
return A[1] as a fraction or zero
|}
5 <span style="color:blue">BRNOU</span>
22 <span style="color:blue">BRNOU</span>
{{out}}
<pre>
2: 0
1: (854513,138)
</pre>
 
===HP-49+ version===
Latest RPL implementations can natively handle long fractions and generate Bernoulli numbers.
{{works with|HP|49}}
≪ { }
0 ROT '''FOR''' n
'''IF''' n 2 > LASTARG MOD AND NOT '''THEN''' n IBERNOULLI + '''END'''
'''NEXT'''
≫ '<span style="color:blue">TASK</span>' STO
 
60 <span style="color:blue">TASK</span>
{{out}}
<pre>
1: {1 -1/2 1/6 -1/30 1/42 -1/30 5/66 -691/2730 7/6 -3617/510 43867/798 -174611/330 854513/138 -236364091/2730 8553103/6 -23749461029/870 8615841276005/14322 -7709321041217/510 2577687858367/6 -26315271553053477373/1919190 2929993913841559/6 -261082718496449122051/13530 1520097643918070802691/1806 -27833269579301024235023/690 596451111593912163277961/282 -5609403368997817686249127547/46410 495057205241079648212477525/66 -801165718135489957347924991853/1590 9149963634884862421418123812691/798 -2479392929313226753685415739663229/870 84483613348880041862046775994036021/354 -1215233140483755572040304994079820246041491/56786730}
</pre>
Runs in 3 minutes 40 on a HP-50g, against 1 hour and 30 minutes if calculating Bernoulli numbers with the above function.
 
=={{header|Ruby}}==
{{trans|Python}}
<langsyntaxhighlight lang="ruby">bernoulli = Enumerator.new do |y|
ar = []
0.step do |m|
Line 3,462 ⟶ 4,054:
b_nums.each_with_index {|b,i| puts "B(%2i) = %*i/%i" % [i, width, b.numerator, b.denominator] unless b.zero? }
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,501 ⟶ 4,093:
=={{header|Rust}}==
 
<langsyntaxhighlight lang="rust">// 2.5 implementations presented here: naive, optimized, and an iterator using
// the optimized function. The speeds vary significantly: relative
// speeds of optimized:iterator:naive implementations is 625:25:1.
Line 3,650 ⟶ 4,242:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,686 ⟶ 4,278:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
 
=={{header|Scala}}==
'''With Custom Rational Number Class'''<br/>
(code will run in Scala REPL with a cut-and-paste without need for a third-party library)
<langsyntaxhighlight lang="scala">/** Roll our own pared-down BigFraction class just for these Bernoulli Numbers */
case class BFraction( numerator:BigInt, denominator:BigInt ) {
require( denominator != BigInt(0), "Denominator cannot be zero" )
Line 3,739 ⟶ 4,330:
println( f"$label%-6s $num / ${b.den}" )
}}
</syntaxhighlight>
</lang>
{{out}}
<pre>b(0) 1 / 1
Line 3,774 ⟶ 4,365:
b(60) -1215233140483755572040304994079820246041491 / 56786730
</pre>
=={{header|Scheme}}==
{{works with|Chez Scheme}}
<syntaxhighlight lang="scheme">; Return the n'th Bernoulli number.
 
(define bernoulli
(lambda (n)
(let ((a (make-vector (1+ n))))
(do ((m 0 (1+ m)))
((> m n))
(vector-set! a m (/ 1 (1+ m)))
(do ((j m (1- j)))
((< j 1))
(vector-set! a (1- j) (* j (- (vector-ref a (1- j)) (vector-ref a j))))))
(vector-ref a 0))))
 
; Convert a rational to a string. If an integer, ends with "/1".
 
(define rational->string
(lambda (rational)
(format "~a/~a" (numerator rational) (denominator rational))))
 
; Returns the string length of the numerator of a rational.
 
(define rational-numerator-length
(lambda (rational)
(string-length (format "~a" (numerator rational)))))
 
; Formats a rational with left-padding such that total length to the slash is as given.
 
(define rational-padded
(lambda (rational total-length-to-slash)
(let* ((length-padding (- total-length-to-slash (rational-numerator-length rational)))
(padding-string (make-string length-padding #\ )))
(string-append padding-string (rational->string rational)))))
 
; Return the Bernoulli numbers 0 through n in a list.
 
(define make-bernoulli-list
(lambda (n)
(if (= n 0)
(list (bernoulli n))
(append (make-bernoulli-list (1- n)) (list (bernoulli n))))))
 
; Print the non-zero Bernoulli numbers 0 through 60 aligning the slashes.
 
(let* ((bernoullis-list (make-bernoulli-list 60))
(numerator-lengths (map rational-numerator-length bernoullis-list))
(max-numerator-length (apply max numerator-lengths)))
(let print-bernoulli ((index 0) (numbers bernoullis-list))
(cond
((null? numbers))
((= 0 (car numbers))
(print-bernoulli (1+ index) (cdr numbers)))
(else
(printf "B(~2@a) = ~a~%" index (rational-padded (car numbers) max-numerator-length))
(print-bernoulli (1+ index) (cdr numbers))))))</syntaxhighlight>
{{out}}
<pre>$ scheme --script bernoulli.scm
B( 0) = 1/1
B( 1) = 1/2
B( 2) = 1/6
B( 4) = -1/30
B( 6) = 1/42
B( 8) = -1/30
B(10) = 5/66
B(12) = -691/2730
B(14) = 7/6
B(16) = -3617/510
B(18) = 43867/798
B(20) = -174611/330
B(22) = 854513/138
B(24) = -236364091/2730
B(26) = 8553103/6
B(28) = -23749461029/870
B(30) = 8615841276005/14322
B(32) = -7709321041217/510
B(34) = 2577687858367/6
B(36) = -26315271553053477373/1919190
B(38) = 2929993913841559/6
B(40) = -261082718496449122051/13530
B(42) = 1520097643918070802691/1806
B(44) = -27833269579301024235023/690
B(46) = 596451111593912163277961/282
B(48) = -5609403368997817686249127547/46410
B(50) = 495057205241079648212477525/66
B(52) = -801165718135489957347924991853/1590
B(54) = 29149963634884862421418123812691/798
B(56) = -2479392929313226753685415739663229/870
B(58) = 84483613348880041862046775994036021/354
B(60) = -1215233140483755572040304994079820246041491/56786730</pre>
=={{header|Seed7}}==
The program below uses [http://seed7.sourceforge.net/manual/types.htm#bigRational bigRational]
Line 3,782 ⟶ 4,462:
function automatically writes repeating decimals in parentheses, when necessary.
 
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "bigrat.s7i";
 
Line 3,815 ⟶ 4,495:
end if;
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 3,852 ⟶ 4,532:
B(60) = -1215233140483755572040304994079820246041491 / 56786730 -21399949257225333665810744765191097.3(926741511617238745742183076926598872659158222352299560126106)
</pre>
 
=={{header|Sidef}}==
Built-in:
<langsyntaxhighlight lang="ruby">say bernoulli(42).as_frac #=> 1520097643918070802691/1806</langsyntaxhighlight>
 
Recursive solution (with auto-memoization):
<langsyntaxhighlight lang="ruby">func bernoulli_number(n) is cached {
 
n.is_one && return 1/2
Line 3,871 ⟶ 4,550:
var Bn = bernoulli_number(n) || next
printf("B(%2d) = %44s / %s\n", n, Bn.nude)
}</langsyntaxhighlight>
 
Using Ramanujan's congruences (pretty fast):
<langsyntaxhighlight lang="ruby">func ramanujan_bernoulli_number(n) is cached {
 
return 1/2 if n.is_one
Line 3,882 ⟶ 4,561:
binomial(n+3, n - 6*k) * __FUNC__(n - 6*k)
})) / binomial(n+3, n)
}</langsyntaxhighlight>
 
Using Euler's product formula for the Riemann zeta function and the Von Staudt–Clausen theorem (very fast):
<langsyntaxhighlight lang="ruby">func bernoulli_number_from_zeta(n) {
 
n.is_zero && return 1
Line 3,899 ⟶ 4,578:
 
(-1)**(n/2 + 1) * int(ceil(d*K / z)) / d
}</langsyntaxhighlight>
 
The Akiyama–Tanigawa algorithm:
<langsyntaxhighlight lang="ruby">func bernoulli_print {
var a = []
for m in (0..60) {
Line 3,914 ⟶ 4,593:
}
 
bernoulli_print()</langsyntaxhighlight>
 
{{out}}
Line 3,951 ⟶ 4,630:
B(60) = -1215233140483755572040304994079820246041491 / 56786730
</pre>
 
=={{header|SPAD}}==
{{works with|FriCAS, OpenAxiom, Axiom}}
<syntaxhighlight lang="spad">
<lang SPAD>
for n in 0..60 | (b:=bernoulli(n)$INTHEORY; b~=0) repeat print [n,b]
</syntaxhighlight>
</lang>
Package:[http://fricas.github.io/api/IntegerNumberTheoryFunctions.html?highlight=bernoulli IntegerNumberTheoryFunctions]
 
Line 4,060 ⟶ 4,738:
Type: Void
</pre>
 
=={{header|Swift}}==
 
Line 4,067 ⟶ 4,744:
Uses the Frac type defined in the [http://rosettacode.org/wiki/Arithmetic/Rational#Swift Rational] task.
 
<langsyntaxhighlight Swiftlang="swift">import BigInt
 
public func bernoulli<T: BinaryInteger & SignedNumeric>(n: Int) -> Frac<T> {
Line 4,095 ⟶ 4,772:
 
print("B(\(n)) = \(b)")
}</langsyntaxhighlight>
 
{{out}}
Line 4,131 ⟶ 4,808:
B(58) = Frac(84483613348880041862046775994036021 / 354)
B(60) = Frac(-1215233140483755572040304994079820246041491 / 56786730)</pre>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc bernoulli {n} {
for {set m 0} {$m <= $n} {incr m} {
lappend A [list 1 [expr {$m + 1}]]
Line 4,158 ⟶ 4,834:
foreach {n num denom} $result {
puts [format {B_%-2d = %*lld/%lld} $n $len $num $denom]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,194 ⟶ 4,870:
B_60 = -1215233140483755572040304994079820246041491/56786730
</pre>
 
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|2013}}
{{libheader|System.Numerics}}
<langsyntaxhighlight lang="vbnet">' Bernoulli numbers - vb.net - 06/03/2017
Imports System.Numerics 'BigInteger
 
Line 4,247 ⟶ 4,922:
End Sub 'bernoulli_BigInt
End Module 'Bernoulli_numbers</langsyntaxhighlight>
{{out}}
<pre>
Line 4,283 ⟶ 4,958:
B(60)=-1215233140483755572040304994079820246041491/56786730
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
{{libheader|Wren-big}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
import "./big" for BigRat
 
var bernoulli = Fn.new { |n|
Line 4,307 ⟶ 4,981:
var b = bernoulli.call(n)
if (b != BigRat.zero) Fmt.print("B($2d) = $44i / $i", n, b.num, b.den)
}</langsyntaxhighlight>
 
{{out}}
Line 4,348 ⟶ 5,022:
{{trans|EchoLisp}}
Uses lib GMP (GNU MP Bignum Library).
<langsyntaxhighlight lang="zkl">class Rational{ // Weenie Rational class, can handle BigInts
fcn init(_a,_b){ var a=_a, b=_b; normalize(); }
fcn toString{ "%50d / %d".fmt(a,b) }
Line 4,367 ⟶ 5,041:
}
fcn __opDiv(n){ self(a*n.b,b*n.a) } // Rat / Rat
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">var [const] BN=Import.lib("zklBigNum"); // libGMP (GNU MP Bignum Library)
fcn B(N){ // calculate Bernoulli(n)
var A=List.createLong(100,0); // aka static aka not thread safe
Line 4,376 ⟶ 5,050:
}
A[0]
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach b in ([0..1].chain([2..60,2])){ println("B(%2d)%s".fmt(b,B(b))) }</langsyntaxhighlight>
{{out}}
<pre>
2,120

edits