Skip to content

Instantly share code, notes, and snippets.

@adnan360
Created March 15, 2016 14:19
Show Gist options
  • Save adnan360/13484220a01c48aad32b to your computer and use it in GitHub Desktop.
Save adnan360/13484220a01c48aad32b to your computer and use it in GitHub Desktop.
Get the value of Pi to the 100000th decimal place!
//////////////////////////////////////////////////////////////
// This code was inspired by: http://www.geom.uiuc.edu/~huberty/math5337/groupe/digits.html
// The solution was from rvk in this thread: http://forum.lazarus.freepascal.org/index.php/topic,31955.0.html
// The code was based on Rosetta code: https://rosettacode.org/wiki/Pi#Pascal
//------------------------------------------------------------
// USING INSTRUCTIONS:
// To use it:
// 1. Open up Lazarus <http://lazarus-ide.org>
// 2. Project -> New Project -> Program -> OK
// 3. Select all, then paste this code
// 4. To run the code: Run -> Run
//////////////////////////////////////////////////////////////
program Pi_Spigot;
const
n = 100000;
len = 10 * n div 3;
var
j, k, q, nines, predigit: integer;
a: array[0..len] of longint;
First: boolean;
function OneLoop(i: integer): integer;
var
x: integer;
begin
{Only calculate as far as needed }
{+16 for security digits ~5 decimals}
i := i * 10 div 3 + 16;
if i > len then
i := len;
Result := 0;
repeat {Work backwards}
x := 10 * a[i] + Result * i;
Result := x div (2 * i - 1);
a[i] := x - Result * (2 * i - 1);//x mod (2*i - 1)
Dec(i);
until i <= 0;
end;
begin
First := True;
for j := 1 to len do
a[j] := 2; {Start with 2s}
nines := 0;
predigit := 0; {First predigit is a 0}
for j := 1 to n do
begin
q := OneLoop(n - j);
a[1] := q mod 10;
q := q div 10;
if q = 9 then
nines := nines + 1
else
if q = 10 then
begin
Write(predigit + 1);
for k := 1 to nines do
Write(0); {zeros}
predigit := 0;
nines := 0;
end
else
begin
if predigit > 0 then
begin
Write(predigit);
if First then Write('.');
First := False;
end;
predigit := q;
if nines <> 0 then
begin
for k := 1 to nines do
Write(9);
nines := 0;
end;
end;
end;
writeln(predigit);
ReadLn;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment