Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

3
Task/Pi/00-META.yaml Normal file
View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Pi
note: Irrational numbers

13
Task/Pi/00-TASK.txt Normal file
View file

@ -0,0 +1,13 @@
Create a program to continually calculate and output the next decimal digit of &nbsp; <big><big><math>\pi</math></big></big> &nbsp; (pi).
The program should continue forever (until it is aborted by the user) calculating and outputting each decimal digit in succession.
The output should be a decimal sequence beginning &nbsp; 3.14159265 ...
Note: this task is about &nbsp; ''calculating'' &nbsp; pi. &nbsp; For information on built-in pi constants see [[Real constants and functions]].
Related Task [[Arithmetic-geometric mean/Calculate Pi]]
<br><br>

31
Task/Pi/11l/pi.11l Normal file
View file

@ -0,0 +1,31 @@
V ndigits = 0
V q = BigInt(1)
V r = BigInt(0)
V t = q
V k = q
V n = BigInt(3)
V l = n
V first = 1B
L ndigits < 1'000
I 4 * q + r - t < n * t
print(n, end' )
ndigits++
I ndigits % 70 == 0
print()
I first
first = 0B
print(., end' )
V nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) I/ t) - 10 * n
q *= 10
r = nr
E
V nr = (2 * q + r) * l
V nn = (q * (7 * k + 2) + r * l) I/ (t * l)
q *= k
t *= l
l += 2
k++
n = nn
r = nr

104
Task/Pi/360-Assembly/pi.360 Normal file
View file

@ -0,0 +1,104 @@
* Spigot algorithm do the digits of PI 02/07/2016
PISPIG CSECT
USING PISPIG,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
LR R13,R15 "
SR R0,R0 0
ST R0,MORE more=0
LA R6,1 i=1
LOOPI1 C R6,=A(NBUF) do i=1 to hbound(buf)
BH ELOOPI1 "
SR R9,R9 karray=0
L R7,=A(NVECT) j=hbound(vect)
LR R1,R7 j
SLA R1,2 .
LA R10,VECT-4(R1) r10=@vect(j)
LOOPJ EQU * do j=hbound(vect) to 1 by -1
L R5,=F'100000' 100000
M R4,0(R10) *vect(j)
LR R2,R5 r2=100000*vect(j)
LR R5,R9 karray
MR R4,R7 karray*j
AR R2,R5 r2+karray*j
LR R11,R2 n=100000*vect(j)+karray*j
LR R3,R7 j
SLA R3,1 2*j
BCTR R3,0 2*j-1)
LR R4,R11 n
SRDA R4,32 .
DR R4,R3 n/(2*j-1)
LR R9,R5 karray=n/(2*j-1)
LR R5,R9 karray
MR R4,R3 karray*(2*j-1)
LR R1,R11 n
SR R1,R5 n-karray*(2*j-1)
ST R1,0(R10) vect(j)=n-karray*(2*j-1)
SH R10,=H'4' r10=@vect(j)
BCT R7,LOOPJ end do j
LR R4,R9 karray
SRDA R4,32 .
D R4,=F'100000' karray/100000
LR R11,R5 k=karray/100000
L R2,MORE more
AR R2,R11 +k
LR R1,R6 i
SLA R1,2 .
ST R2,BUF-4(R1) buf(i)=more+k
LR R5,R11 k
M R4,=F'100000' *100000
LR R1,R9 karray
SR R1,R5 -k*100000
ST R1,MORE more=karray-k*100000
LA R6,1(R6) i=i+1
B LOOPI1 end do i
ELOOPI1 L R1,BUF buf(1)
CVD R1,PACKED convert buf(1) to packed decimal
OI PACKED+7,X'0F' prepare unpack
UNPK PG(1),PACKED packed decimal to zoned printable
MVI PG+1,C'.' output '.'
XPRNT PG,80 print buffer
MVC PG,=CL80' ' clear buffer
LA R3,PG pgi=0
LA R6,2 i=2
LOOPI2 C R6,=A(NBUF) do i=2 to hbound(buf)
BH ELOOPI2 "
MVC 0(1,R3),=C' ' output ' '
LA R3,1(R3) pgi=pgi+1
LR R1,R6 i
SLA R1,2 .
L R2,BUF-4(R1) buf(i)
CVD R2,PACKED convert v to packed decimal
OI PACKED+7,X'0F' prepare unpack
UNPK XDEC,PACKED packed decimal to zoned printable
MVC 0(5,R3),XDEC+7 output buf(i) with 5 decimals
LA R3,5(R3) pgi=pgi+5
LR R4,R6 i
BCTR R4,0 i-1
SRDA R4,32 .
D R4,=F'10' (i-1)/10
LTR R4,R4 if (i-1)//10=0
BNZ NOSKIP then
XPRNT PG,80 print buffer
LA R3,PG pgi=0
MVC PG,=CL80' ' clear buffer
NOSKIP LA R6,1(R6) i=i+1
B LOOPI2 end do i
ELOOPI2 L R13,4(0,R13) epilog
LM R14,R12,12(R13) "
XR R15,R15 "
BR R14 exit
LTORG
MORE DS F more
PACKED DS 0D,PL8 packed decimal
PG DC CL80' ' buffer
XDEC DS CL12 temp
BUF DC (NBUF)F'0' buf(nbuf)
VECT DC (NVECT)F'2' vect(nvect) init 2
YREGS
NBUF EQU 201 number of 5 decimals
NVECT EQU 3350 nvect=ceil(nbuf*50/3)
END PISPIG

51
Task/Pi/ALGOL-68/pi.alg Normal file
View file

@ -0,0 +1,51 @@
#!/usr/local/bin/a68g --script #
INT base := 10;
MODE YIELDINT = PROC(INT)VOID;
PROC gen pi digits = (INT decimal places, YIELDINT yield)VOID:
BEGIN
INT nine = base - 1;
INT nines := 0, predigit := 0; # First predigit is a 0 #
[decimal places*10 OVER 3]#LONG# INT digits; # We need 3 times the digits to calculate #
FOR place FROM LWB digits TO UPB digits DO digits[place] := 2 OD; # Start with 2s #
FOR place TO decimal places + 1 DO
INT digit := 0;
FOR i FROM UPB digits BY -1 TO LWB digits DO # Work backwards #
INT x := #SHORTEN#(base*digits[i] + #LENG# digit*i);
digits[i] := x MOD (2*i-1);
digit := x OVER (2*i-1)
OD;
digits[LWB digits] := digit MOD base; digit OVERAB base;
nines :=
IF digit = nine THEN
nines + 1
ELSE
IF digit = base THEN
yield(predigit+1); predigit := 0 ;
FOR repeats TO nines DO yield(0) OD # zeros #
ELSE
IF place NE 1 THEN yield(predigit) FI; predigit := digit;
FOR repeats TO nines DO yield(nine) OD
FI;
0
FI
OD;
yield(predigit)
END;
main:(
INT feynman point = 762; # feynman point + 4 is a good test case #
# the 33rd decimal place is a shorter tricky test case #
INT test decimal places = UPB "3.1415926.......................502"-2;
INT width = ENTIER log(base*(1+small real*10));
# iterate throught the digits as they are being found #
# FOR INT digit IN # gen pi digits(test decimal places#) DO ( #,
## (INT digit)VOID: (
printf(($n(width)d$,digit))
)
# OD #);
print(new line)
)

112
Task/Pi/Ada/pi.ada Normal file
View file

@ -0,0 +1,112 @@
with Ada.Command_Line;
with Ada.Text_IO;
with GNU_Multiple_Precision.Big_Integers;
with GNU_Multiple_Precision.Big_Rationals;
use GNU_Multiple_Precision;
procedure Pi_Digits is
type Int is mod 2 ** 64;
package Int_To_Big is new Big_Integers.Modular_Conversions (Int);
-- constants
Zero : constant Big_Integer := Int_To_Big.To_Big_Integer (0);
One : constant Big_Integer := Int_To_Big.To_Big_Integer (1);
Two : constant Big_Integer := Int_To_Big.To_Big_Integer (2);
Three : constant Big_Integer := Int_To_Big.To_Big_Integer (3);
Four : constant Big_Integer := Int_To_Big.To_Big_Integer (4);
Ten : constant Big_Integer := Int_To_Big.To_Big_Integer (10);
-- type LFT = (Integer, Integer, Integer, Integer
type LFT is record
Q, R, S, T : Big_Integer;
end record;
-- extr :: LFT -> Integer -> Rational
function Extr (T : LFT; X : Big_Integer) return Big_Rational is
use Big_Integers;
Result : Big_Rational;
begin
-- extr (q,r,s,t) x = ((fromInteger q) * x + (fromInteger r)) /
-- ((fromInteger s) * x + (fromInteger t))
Big_Rationals.Set_Numerator (Item => Result,
New_Value => T.Q * X + T.R,
Canonicalize => False);
Big_Rationals.Set_Denominator (Item => Result,
New_Value => T.S * X + T.T);
return Result;
end Extr;
-- unit :: LFT
function Unit return LFT is
begin
-- unit = (1,0,0,1)
return LFT'(Q => One, R => Zero, S => Zero, T => One);
end Unit;
-- comp :: LFT -> LFT -> LFT
function Comp (T1, T2 : LFT) return LFT is
use Big_Integers;
begin
-- comp (q,r,s,t) (u,v,w,x) = (q*u+r*w,q*v+r*x,s*u+t*w,s*v+t*x)
return LFT'(Q => T1.Q * T2.Q + T1.R * T2.S,
R => T1.Q * T2.R + T1.R * T2.T,
S => T1.S * T2.Q + T1.T * T2.S,
T => T1.S * T2.R + T1.T * T2.T);
end Comp;
-- lfts = [(k, 4*k+2, 0, 2*k+1) | k<-[1..]
K : Big_Integer := Zero;
function LFTS return LFT is
use Big_Integers;
begin
K := K + One;
return LFT'(Q => K,
R => Four * K + Two,
S => Zero,
T => Two * K + One);
end LFTS;
-- next z = floor (extr z 3)
function Next (T : LFT) return Big_Integer is
begin
return Big_Rationals.To_Big_Integer (Extr (T, Three));
end Next;
-- safe z n = (n == floor (extr z 4)
function Safe (T : LFT; N : Big_Integer) return Boolean is
begin
return N = Big_Rationals.To_Big_Integer (Extr (T, Four));
end Safe;
-- prod z n = comp (10, -10*n, 0, 1)
function Prod (T : LFT; N : Big_Integer) return LFT is
use Big_Integers;
begin
return Comp (LFT'(Q => Ten, R => -Ten * N, S => Zero, T => One), T);
end Prod;
procedure Print_Pi (Digit_Count : Positive) is
Z : LFT := Unit;
Y : Big_Integer;
Count : Natural := 0;
begin
loop
Y := Next (Z);
if Safe (Z, Y) then
Count := Count + 1;
Ada.Text_IO.Put (Big_Integers.Image (Y));
exit when Count >= Digit_Count;
Z := Prod (Z, Y);
else
Z := Comp (Z, LFTS);
end if;
end loop;
end Print_Pi;
N : Positive := 250;
begin
if Ada.Command_Line.Argument_Count = 1 then
N := Positive'Value (Ada.Command_Line.Argument (1));
end if;
Print_Pi (N);
end Pi_Digits;

View file

@ -0,0 +1,51 @@
10 REM ADOPTED FROM COMMODORE BASIC
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
30 LN = INT(10*N/3)+16
40 ND = 1
50 DIM A(LN)
60 N9 = 0
70 PD = 0:REM FIRST PRE-DIGIT IS A 0
80 REM
90 FOR J = 1 TO LN
100 A(J-1) = 2:REM START WITH 2S
110 NEXT J
120 REM
130 FOR J = 1 TO N
140 Q = 0
150 FOR I = LN TO 1 STEP -1:REM WORK BACKWARDS
160 X = 10*A(I-1) + Q*I
170 A(I-1) = X - (2*I-1)*INT(X/(2*I-1)):REM X - INT ( X / Y) * Y
180 Q = INT(X/(2*I - 1))
190 NEXT I
200 A(0) = Q-10*INT(Q/10)
210 Q = INT(Q/10)
220 IF Q=9 THEN N9 = N9 + 1: GOTO 450
240 IF Q<>10 THEN GOTO 350
250 REM Q == 10
260 D = PD+1: GOSUB 500
270 IF N9 <= 0 THEN GOTO 320
280 FOR K = 1 TO N9
290 D = 0: GOSUB 500
300 NEXT K
310 REM END IF
320 PD = 0
330 N9 = 0
335 GOTO 450
340 REM Q <> 10
350 D = PD: GOSUB 500
360 PD = Q
370 IF N9 = 0 THEN GOTO 450
380 FOR K = 1 TO N9
390 D = 9: GOSUB 500
400 NEXT K
410 N9 = 0
450 NEXT J
460 PRINT PD
470 END
480 REM
490 REM OUTPUT DIGITS
500 IF ND=0 THEN PRINT D;: RETURN
510 IF D=0 THEN RETURN
520 PRINT D;".";
530 ND = 0
550 RETURN

37
Task/Pi/Arturo/pi.arturo Normal file
View file

@ -0,0 +1,37 @@
q: 1
r: 0
t: 1
k: 1
n: 3
l: 3
d: 0
dotWritten: false
while [true][
if? (n*t) > (4*q)+r-t [
d: d+1
prints n
unless dotWritten [
prints "."
dotWritten: true
d: d+1
]
if 0 = d%80 -> prints "\n"
nr: 10*(r - n*t)
n: ((10*(r + 3*q)) / t) - 10*n
q: q*10
r: nr
]
else [
nr: (r + 2*q) * l
nn: ((q*(2 + 7*k)) + r*l) / (t*l)
q: q*k
t: t*l
l: l+2
k: k+1
n: nn
r: nr
]
]

66
Task/Pi/AutoHotkey/pi.ahk Normal file
View file

@ -0,0 +1,66 @@
#NoEnv
#SingleInstance, Force
SetBatchLines, -1
#Include mpl.ahk
dot:=".", i:=0
, MP_SET(q, "1")
, MP_SET(r, "0")
, MP_SET(t, "1")
, MP_SET(k, "1")
, MP_SET(n, "3")
, MP_SET(l, "3")
, MP_SET(ONE, "1")
, MP_SET(TWO, "2")
, MP_SET(THREE, "3")
, MP_SET(FOUR, "4")
, MP_SET(SEVEN, "7")
, MP_SET(TEN, "10")
Loop
{
MP_MUL(q4, q, FOUR)
, MP_ADD(q4r, q4, r)
, MP_SUB(q4rt, q4r, t)
, MP_MUL(tn, t, n)
If (MP_CMP(q4rt,tn) = -1)
{
s := MP_DEC(n) . dot
OutputDebug %s%
dot := ""
, i++
, MP_MUL(tn, t, n)
, MP_SUB(rtn, r, tn)
, MP_MUL(nr, rtn, TEN)
, MP_MUL(q3, q, THREE)
, MP_ADD(q3r, q3, r)
, MP_DIV(q3rt, remainder, q3r, t)
, MP_SUB(q3rtn, q3rt, n)
, MP_MUL(n, q3rtn, TEN)
, MP_MUL(tmp, q, TEN)
, MP_CPY(q, tmp)
, MP_CPY(r, nr)
}
Else
{
MP_MUL(q2, q, TWO)
, MP_ADD(q2r, q2, r)
, MP_MUL(nr, q2r, l)
, MP_MUL(k7, k, SEVEN)
, MP_ADD(k72, k7, TWO)
, MP_MUL(qk, q, k72)
, MP_MUL(rl, r, l)
, MP_ADD(qkrl, qk, rl)
, MP_MUL(tl, t, l)
, MP_DIV(nn, remainder, qkrl, tl)
, MP_MUL(tmp, q, k)
, MP_CPY(q, tmp)
, MP_MUL(tmp, t, l)
, MP_CPY(t, tmp)
, MP_ADD(tmp, l, TWO)
, MP_CPY(l, tmp)
, MP_ADD(tmp, k, ONE)
, MP_CPY(k, tmp)
, MP_CPY(n, nn)
, MP_CPY(r, nr)
}
}

59
Task/Pi/BASIC256/pi.basic Normal file
View file

@ -0,0 +1,59 @@
cls
n =1000
len = 10*n \ 4
needdecimal = true
dim a(len)
nines = 0
predigit = 0 # {First predigit is a 0}
for j = 1 to len
a[j-1] = 2 # {Start with 2s}
next j
for j = 1 to n
q = 0
for i = len to 1 step -1
# {Work backwards}
x = 10*a[i-1] + q*i
a[i-1] = x % (2*i - 1)
q = x \ (2*i - 1)
next i
a[0] = q % 10
q = q \ 10
if q = 9 then
nines = nines + 1
else
if q = 10 then
d = predigit+1: gosub outputd
if nines > 0 then
for k = 1 to nines
d = 0: gosub outputd
next k
end if
predigit = 0
nines = 0
else
d = predigit: gosub outputd
predigit = q
if nines <> 0 then
for k = 1 to nines
d = 9: gosub outputd
next k
nines = 0
end if
end if
end if
next j
print predigit
end
outputd:
if needdecimal then
if d = 0 then return
print d + ".";
needdecimal = false
else
print d;
end if
return

View file

@ -0,0 +1,23 @@
WIDTH 80
M% = (HIMEM-END-1000) / 4
DIM B%(M%)
FOR I% = 0 TO M% : B%(I%) = 20 : NEXT
E% = 0
L% = 2
FOR C% = M% TO 14 STEP -7
D% = 0
A% = C%*2-1
FOR P% = C% TO 1 STEP -1
D% = D%*P% + B%(P%)*&64
B%(P%) = D% MOD A%
D% DIV= A%
A% -= 2
NEXT
CASE TRUE OF
WHEN D% = 99: E% = E% * 100 + D% : L% += 2
WHEN C% = M%: PRINT ;(D% DIV 100) / 10; : E% = D% MOD 100
OTHERWISE:
PRINT RIGHT$(STRING$(L%,"0") + STR$(E% + D% DIV 100),L%);
E% = D% MOD 100 : L% = 2
ENDCASE
NEXT

View file

@ -0,0 +1,23 @@
DIM P% 32
[OPT 2 :.pidig mov ebp,eax :.pi1 imul edx,ecx : mov eax,[ebx+ecx*4]
imul eax,100 : add eax,edx : cdq : div ebp : mov [ebx+ecx*4],edx
mov edx,eax : sub ebp,2 : loop pi1 : mov eax,edx : ret :]
WIDTH 80
M% = (HIMEM-END-1000) / 4
DIM B%(M%) : B% = ^B%(0)
FOR I% = 0 TO M% : B%(I%) = 20 : NEXT
E% = 0
L% = 2
FOR C% = M% TO 14 STEP -7
D% = 0
A% = C%*2-1
D% = USR(pidig)
CASE TRUE OF
WHEN D% = 99: E% = E% * 100 + D% : L% += 2
WHEN C% = M%: PRINT ;(D% DIV 100) / 10; : E% = D% MOD 100
OTHERWISE:
PRINT RIGHT$(STRING$(L%,"0") + STR$(E% + D% DIV 100),L%);
E% = D% MOD 100 : L% = 2
ENDCASE
NEXT

30
Task/Pi/Bc/pi.bc Normal file
View file

@ -0,0 +1,30 @@
#!/usr/bin/bc -l
scaleinc= 20
define zeropad ( n ) {
auto m
for ( m= scaleinc - 1; m > 0; --m ) {
if ( n < 10^m ) {
print "0"
}
}
return ( n )
}
wantscale= scaleinc - 2
scale= wantscale + 2
oldpi= 4*a(1)
scale= wantscale
oldpi= oldpi / 1
oldpi
while( 1 ) {
wantscale= wantscale + scaleinc
scale= wantscale + 2
pi= 4*a(1)
scale= 0
digits= ((pi - oldpi) * 10^wantscale) / 1
zeropad( digits )
scale= wantscale
oldpi= pi / 1
}

View file

@ -0,0 +1,29 @@
( pi
= f,q r t k n l,first
. !arg:((=?f),?q,?r,?t,?k,?n,?l)
& yes:?first
& whl
' ( 4*!q+!r+-1*!t+-1*!n*!t:<0
& f$!n
& ( !first:yes
& f$"."
& no:?first
|
)
& "compute and update variables for next cycle"
& 10*(!r+-1*!n*!t):?nr
& div$(10*(3*!q+!r).!t)+-10*!n:?n
& !q*10:?q
& !nr:?r
| "compute and update variables for next cycle"
& (2*!q+!r)*!l:?nr
& div$(!q*(7*!k+2)+!r*!l.!t*!l):?nn
& !q*!k:?q
& !t*!l:?t
& !l+2:?l
& !k+1:?k
& !nn:?n
& !nr:?r
)
)
& pi$((=.put$!arg),1,0,1,1,3,3)

56
Task/Pi/C++/pi.cpp Normal file
View file

@ -0,0 +1,56 @@
#include <iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
class Gospers
{
cpp_int q, r, t, i, n;
public:
// use Gibbons spigot algorith based on the Gospers series
Gospers() : q{1}, r{0}, t{1}, i{1}
{
++*this; // move to the first digit
}
// the ++ prefix operator will move to the next digit
Gospers& operator++()
{
n = (q*(27*i-12)+5*r) / (5*t);
while(n != (q*(675*i-216)+125*r)/(125*t))
{
r = 3*(3*i+1)*(3*i+2)*((5*i-2)*q+r);
q = i*(2*i-1)*q;
t = 3*(3*i+1)*(3*i+2)*t;
i++;
n = (q*(27*i-12)+5*r) / (5*t);
}
q = 10*q;
r = 10*r-10*n*t;
return *this;
}
// the dereference operator will give the current digit
int operator*()
{
return (int)n;
}
};
int main()
{
Gospers g;
std::cout << *g << "."; // print the first digit and the decimal point
for(;;) // run forever
{
std::cout << *++g; // increment to the next digit and print
}
}

50
Task/Pi/C-sharp/pi-1.cs Normal file
View file

@ -0,0 +1,50 @@
using System;
using System.Numerics;
namespace PiCalc {
internal class Program {
private readonly BigInteger FOUR = new BigInteger(4);
private readonly BigInteger SEVEN = new BigInteger(7);
private readonly BigInteger TEN = new BigInteger(10);
private readonly BigInteger THREE = new BigInteger(3);
private readonly BigInteger TWO = new BigInteger(2);
private BigInteger k = BigInteger.One;
private BigInteger l = new BigInteger(3);
private BigInteger n = new BigInteger(3);
private BigInteger q = BigInteger.One;
private BigInteger r = BigInteger.Zero;
private BigInteger t = BigInteger.One;
public void CalcPiDigits() {
BigInteger nn, nr;
bool first = true;
while (true) {
if ((FOUR*q + r - t).CompareTo(n*t) == -1) {
Console.Write(n);
if (first) {
Console.Write(".");
first = false;
}
nr = TEN*(r - (n*t));
n = TEN*(THREE*q + r)/t - (TEN*n);
q *= TEN;
r = nr;
} else {
nr = (TWO*q + r)*l;
nn = (q*(SEVEN*k) + TWO + r*l)/(t*l);
q *= k;
t *= l;
l += TWO;
k += BigInteger.One;
n = nn;
r = nr;
}
}
}
private static void Main(string[] args) {
new Program().CalcPiDigits();
}
}
}

71
Task/Pi/C-sharp/pi-2.cs Normal file
View file

@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace EnumeratePi {
class Program {
private const int N = 60;
private const string ZS = " +-";
static void Main() {
Console.WriteLine("Digits of PI");
Console.WriteLine(new string('=', N + 13));
Console.WriteLine("Decimal : {0}", string.Concat(PiDigits(10).Take(N).Select(_ => _.ToString("d"))));
Console.WriteLine("Binary : {0}", string.Concat(PiDigits(2).Take(N).Select(_ => _.ToString("d"))));
Console.WriteLine("Quaternary : {0}", string.Concat(PiDigits(4).Take(N).Select(_ => _.ToString("d"))));
Console.WriteLine("Octal : {0}", string.Concat(PiDigits(8).Take(N).Select(_ => _.ToString("d"))));
Console.WriteLine("Hexadecimal: {0}", string.Concat(PiDigits(16).Take(N).Select(_ => _.ToString("x"))));
Console.WriteLine("Alphabetic : {0}", string.Concat(PiDigits(26).Take(N).Select(_ => (char) ('A' + _))));
Console.WriteLine("Fun : {0}", string.Concat(PiDigits(ZS.Length).Take(N).Select(_ => ZS[(int)_])));
Console.WriteLine("Nibbles : {0}", string.Concat(PiDigits(0x10).Take(N/2).Select(_ => string.Format("{0:x1} ", _))));
Console.WriteLine("Bytes : {0}", string.Concat(PiDigits(0x100).Take(N/3).Select(_ => string.Format("{0:x2} ", _))));
Console.WriteLine("Words : {0}", string.Concat(PiDigits(0x10000).Take(N/5).Select(_ => string.Format("{0:x4} ", _))));
Console.WriteLine("Dwords : {0}", string.Concat(PiDigits(0x100000000).Take(N/9).Select(_ => string.Format("{0:x8} ", _))));
Console.WriteLine(new string('=', N + 13));
Console.WriteLine("* press any key to exit *");
Console.ReadKey();
}
/// <summary>Enumerates the digits of PI.</summary>
/// <param name="b">Base of the Numeral System to use for the resulting digits (default = Base.Decimal (10)).</param>
/// <returns>The digits of PI.</returns>
static IEnumerable<long> PiDigits(long b = 10) {
BigInteger
k = 1,
l = 3,
n = 3,
q = 1,
r = 0,
t = 1
;
// skip integer part
var nr = b * (r - t * n);
n = b * (3 * q + r) / t - b * n;
q *= b;
r = nr;
for (; ; ) {
var tn = t * n;
if (4 * q + r - t < tn) {
yield return (long)n;
nr = b * (r - tn);
n = b * (3 * q + r) / t - b * n;
q *= b;
} else {
t *= l;
nr = (2 * q + r) * l;
var nn = (q * (7 * k) + 2 + r * l) / t;
q *= k;
l += 2;
++k;
n = nn;
}
r = nr;
}
}
}
}

68
Task/Pi/C/pi.c Normal file
View file

@ -0,0 +1,68 @@
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
mpz_t tmp1, tmp2, t5, t239, pows;
void actan(mpz_t res, unsigned long base, mpz_t pows)
{
int i, neg = 1;
mpz_tdiv_q_ui(res, pows, base);
mpz_set(tmp1, res);
for (i = 3; ; i += 2) {
mpz_tdiv_q_ui(tmp1, tmp1, base * base);
mpz_tdiv_q_ui(tmp2, tmp1, i);
if (mpz_cmp_ui(tmp2, 0) == 0) break;
if (neg) mpz_sub(res, res, tmp2);
else mpz_add(res, res, tmp2);
neg = !neg;
}
}
char * get_digits(int n, size_t* len)
{
mpz_ui_pow_ui(pows, 10, n + 20);
actan(t5, 5, pows);
mpz_mul_ui(t5, t5, 16);
actan(t239, 239, pows);
mpz_mul_ui(t239, t239, 4);
mpz_sub(t5, t5, t239);
mpz_ui_pow_ui(pows, 10, 20);
mpz_tdiv_q(t5, t5, pows);
*len = mpz_sizeinbase(t5, 10);
return mpz_get_str(0, 0, t5);
}
int main(int c, char **v)
{
unsigned long accu = 16384, done = 0;
size_t got;
char *s;
mpz_init(tmp1);
mpz_init(tmp2);
mpz_init(t5);
mpz_init(t239);
mpz_init(pows);
while (1) {
s = get_digits(accu, &got);
/* write out digits up to the last one not preceding a 0 or 9*/
got -= 2; /* -2: length estimate may be longer than actual */
while (s[got] == '0' || s[got] == '9') got--;
printf("%.*s", (int)(got - done), s + done);
free(s);
done = got;
/* double the desired digits; slows down at least cubically */
accu *= 2;
}
return 0;
}

View file

@ -0,0 +1,51 @@
100 REM adopted from Applesoft BASIC
110 n = 100 : rem n may be increased, but will slow execution
120 ln = int(10*n/3)+16
130 nd = 1
140 dim a(ln)
150 n9 = 0
160 pd = 0 : rem First pre-digit is a 0
170 rem
180 for j = 1 to ln
190 a(j-1) = 2 : rem Start wirh 2S
200 next j
210 rem
220 for j = 1 to n
230 q = 0
240 for i = ln to 1 step -1 : rem Work backwards
250 x = 10*a(i-1)+q*i
260 a(i-1) = x-(2*i-1)*int(x/(2*i-1)) : rem X - Int ( X / Y) * Y
270 q = int(x/(2*i-1))
280 next i
290 a(0) = q-10*int(q/10)
300 q = int(q/10)
310 if q = 9 then n9 = n9+1 : goto 510
320 if q <> 10 then goto 440
330 rem Q == 10
340 d = pd+1 : gosub 560
350 if n9 <= 0 then goto 400
360 for k = 1 to n9
370 d = 0 : gosub 560
380 next k
390 rem End If
400 pd = 0
410 n9 = 0
420 goto 510
430 rem Q <> 10
440 d = pd : gosub 560
450 pd = q
460 if n9 = 0 then goto 510
470 for k = 1 to n9
480 d = 9 : gosub 560
490 next k
500 n9 = 0
510 next j
520 print str$(pd)
530 end
540 rem
550 rem Output digits
560 if nd = 0 then print str$(d); : return
570 if d = 0 then return
580 print str$(d);".";
590 nd = 0
600 return

38
Task/Pi/Clojure/pi.clj Normal file
View file

@ -0,0 +1,38 @@
(ns pidigits
(:gen-class))
(def calc-pi
; integer division rounding downwards to -infinity
(let [div (fn [x y] (long (Math/floor (/ x y))))
; Computations performed after yield clause in Python code
update-after-yield (fn [[q r t k n l]]
(let [nr (* 10 (- r (* n t)))
nn (- (div (* 10 (+ (* 3 q) r)) t) (* 10 n))
nq (* 10 q)]
[nq nr t k nn l]))
; Update of else clause in Python code: if (< (- (+ (* 4 q) r) t) (* n t))
update-else (fn [[q r t k n l]]
(let [nr (* (+ (* 2 q) r) l)
nn (div (+ (* q 7 k) 2 (* r l)) (* t l))
nq (* k q)
nt (* l t)
nl (+ 2 l)
nk (+ 1 k)]
[nq nr nt nk nn nl]))
; Compute the lazy sequence of pi digits translating the Python code
pi-from (fn pi-from [[q r t k n l]]
(if (< (- (+ (* 4 q) r) t) (* n t))
(lazy-seq (cons n (pi-from (update-after-yield [q r t k n l]))))
(recur (update-else [q r t k n l]))))]
; Use Clojure big numbers to perform the math (avoid integer overflow)
(pi-from [1N 0N 1N 1N 3N 3N])))
;; Indefinitely Output digits of pi, with 40 characters per line
(doseq [[i q] (map-indexed vector calc-pi)]
(when (= (mod i 40) 0)
(println))
(print q))

View file

@ -0,0 +1,51 @@
10 PRINT CHR$(147)
20 N = 100: REM N MAY BE INCREASED, BUT WILL SLOW EXECUTION
30 LN = INT(10*N/3)+16
40 ND = 1
50 DIM A(LN)
60 N9 = 0
70 PD = 0:REM FIRST PRE-DIGIT IS A 0
80 REM
90 FOR J = 1 TO LN
100 A(J-1) = 2:REM START WITH 2S
110 NEXT J
120 REM
130 FOR J = 1 TO N
140 Q = 0
150 FOR I = LN TO 1 STEP -1:REM WORK BACKWARDS
160 X = 10*A(I-1) + Q*I
170 A(I-1) = X - (2*I-1)*INT(X/(2*I-1)):REM X - INT ( X / Y) * Y
180 Q = INT(X/(2*I - 1))
190 NEXT I
200 A(0) = Q-10*INT(Q/10)
210 Q = INT(Q/10)
220 IF Q=9 THEN N9 = N9 + 1: GOTO 450
240 IF Q<>10 THEN GOTO 350
250 REM Q == 10
260 D = PD+1: GOSUB 500
270 IF N9 <= 0 THEN GOTO 320
280 FOR K = 1 TO N9
290 D = 0: GOSUB 500
300 NEXT K
310 REM END IF
320 PD = 0
330 N9 = 0
335 GOTO 450
340 REM Q <> 10
350 D = PD: GOSUB 500
360 PD = Q
370 IF N9 = 0 THEN GOTO 450
380 FOR K = 1 TO N9
390 D = 9: GOSUB 500
400 NEXT K
410 N9 = 0
450 NEXT J
460 PRINT RIGHT$(STR$(PD),1)
470 END
480 REM
490 REM OUTPUT DIGITS
500 IF ND=0 THEN PRINT RIGHT$(STR$(D),1);: RETURN
510 IF D=0 THEN RETURN
520 PRINT RIGHT$(STR$(D),1);".";
530 ND = 0
550 RETURN

View file

@ -0,0 +1,25 @@
(defun pi-spigot ()
(labels
((g (q r t1 k n l)
(cond
((< (- (+ (* 4 q) r) t1)
(* n t1))
(princ n)
(g (* 10 q)
(* 10 (- r (* n t1)))
t1
k
(- (floor (/ (* 10 (+ (* 3 q) r))
t1))
(* 10 n))
l))
(t
(g (* q k)
(* (+ (* 2 q) r) l)
(* t1 l)
(+ k 1)
(floor (/ (+ (* q (+ (* 7 k) 2))
(* r l))
(* t1 l)))
(+ l 2))))))
(g 1 0 1 1 3 3)))

View file

@ -0,0 +1,30 @@
require "big"
def pi
q, r, t, k, n, l = [1, 0, 1, 1, 3, 3].map { |n| BigInt.new(n) }
dot_written = false
loop do
if 4*q + r - t < n*t
yield n
unless dot_written
yield '.'
dot_written = true
end
nr = 10*(r - n*t)
n = ((10*(3*q + r)) / t) - 10*n
q *= 10
r = nr
else
nr = (2*q + r) * l
nn = (q*(7*k + 2) + r*l) / (t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
end
end
end
pi { |digit_or_dot| print digit_or_dot; STDOUT.flush }

38
Task/Pi/D/pi-1.d Normal file
View file

@ -0,0 +1,38 @@
import std.stdio, std.conv, std.string;
struct PiDigits {
immutable uint nDigits;
int opApply(int delegate(ref string /*chunk of pi digit*/) dg){
// Maximum width for correct output, for type ulong.
enum size_t width = 9;
enum ulong scale = 10UL ^^ width;
enum ulong initDigit = 2UL * 10UL ^^ (width - 1);
enum string formatString = "%0" ~ text(width) ~ "d";
immutable size_t len = 10 * nDigits / 3;
auto arr = new ulong[len];
arr[] = initDigit;
ulong carry;
foreach (i; 0 .. nDigits / width) {
ulong sum;
foreach_reverse (j; 0 .. len) {
auto quo = sum * (j + 1) + scale * arr[j];
arr[j] = quo % (j*2 + 1);
sum = quo / (j*2 + 1);
}
auto yield = format(formatString, carry + sum/scale);
if (dg(yield))
break;
carry = sum % scale;
}
return 0;
}
}
void main() {
foreach (d; PiDigits(100))
writeln(d);
}

33
Task/Pi/D/pi-2.d Normal file
View file

@ -0,0 +1,33 @@
import std.stdio, std.bigint;
void main() {
int ndigits = 0;
auto q = BigInt(1);
auto r = BigInt(0);
auto t = q;
auto k = q;
auto n = BigInt(3);
auto l = n;
bool first = true;
while (ndigits < 1_000) {
if (4 * q + r - t < n * t) {
write(n); ndigits++;
if (ndigits % 70 == 0) writeln();
if (first) { first = false; write('.'); }
auto nr = 10 * (r - n * t);
n = ((10 * (3 * q + r)) / t) - 10 * n;
q *= 10;
r = nr;
} else {
auto nr = (2 * q + r) * l;
auto nn = (q * (7 * k + 2) + r * l) / (t * l);
q *= k;
t *= l;
l += 2;
k++;
n = nn;
r = nr;
}
}
}

137
Task/Pi/Delphi/pi.delphi Normal file
View file

@ -0,0 +1,137 @@
unit Pi_BBC_Main;
interface
uses
Classes, Controls, Forms, Dialogs, StdCtrls;
type
TForm1 = class(TForm)
btnRunSpigotAlgo: TButton;
memScreen: TMemo;
procedure btnRunSpigotAlgoClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
fScreenWidth : integer;
fLineBuffer : string;
procedure ClearText();
procedure AddText( const s : string);
procedure FlushText();
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses SysUtils;
// Button clicked to run algorithm
procedure TForm1.btnRunSpigotAlgoClick(Sender: TObject);
var
// BBC Basic variables. Delphi longint is 32 bits.
B : array of longint;
A, C, D, E, I, L, M, P : longint;
// Added for Delphi version
temp : string;
h, j, t : integer;
begin
fScreenWidth := 80;
ClearText();
M := 5368709; // floor( (2^31 - 1)/400 )
// DIM B%(M%) in BBC Basic declares an array [0..M%], i.e. M% + 1 elements
SetLength( B, M + 1);
for I := 0 to M do B[I] := 20;
E := 0;
L := 2;
// FOR C% = M% TO 14 STEP -7
// In Delphi (or at least Delphi 7) the step size in a for loop has to be 1.
// So the BBC Basic FOR loop has been replaced by a repeat loop.
C := M;
repeat
D := 0;
A := C*2 - 1;
for P := C downto 1 do begin
D := D*P + B[P]*$64; // hex notation copied from BBC version
B[P] := D mod A;
D := D div A;
dec( A, 2);
end;
// The BBC CASE statement here amounts to a series of if ... else
if (D = 99) then begin
E := E*100 + D;
inc( L, 2);
end
else if (C = M) then begin
AddText( SysUtils.Format( '%2.1f', [1.0*(D div 100) / 10.0] ));
E := D mod 100;
end
else begin
// PRINT RIGHT$(STRING$(L%,"0") + STR$(E% + D% DIV 100),L%);
// This can't be done so concisely in Delphi 7
SetLength( temp, L);
for j := 1 to L do temp[j] := '0';
temp := temp + SysUtils.IntToStr( E + D div 100);
t := Length( temp);
AddText( Copy( temp, t - L + 1, L));
E := D mod 100;
L := 2;
end;
dec( C, 7);
until (C < 14);
FlushText();
// Delphi addition: Write screen output to a file for checking
h := SysUtils.FileCreate( 'C:\Delphi\PiDigits.txt'); // h = file handle
for j := 0 to memScreen.Lines.Count - 1 do
SysUtils.FileWrite( h, memScreen.Lines[j][1], Length( memScreen.Lines[j]));
SysUtils.FileClose( h);
end;
{=========================== Auxiliary routines ===========================}
// Form created
procedure TForm1.FormCreate(Sender: TObject);
begin
fScreenWidth := 80; // in case not set by the algotithm
ClearText();
end;
// This Delphi version builds each screen line in a buffer and puts
// the line into the TMemo when the buffer is full.
// This is faster than writing to the TMemo a few characters at a time,
// but note that the buffer must be flushed at the end of the program.
procedure TForm1.ClearText();
begin
memScreen.Lines.Clear();
fLineBuffer := '';
end;
procedure TForm1.AddText( const s : string);
var
nrChars, nrLeft : integer;
begin
nrChars := Length( s);
nrLeft := fScreenWidth - Length( fLineBuffer); // nr chars left in line
if (nrChars <= nrLeft) then fLineBuffer := fLineBuffer + s
else begin
fLineBuffer := fLineBuffer + Copy( s, 1, nrLeft);
memScreen.Lines.Add( fLineBuffer);
fLineBuffer := Copy( s, nrLeft + 1, nrChars - nrLeft);
end;
end;
procedure TForm1.FlushText();
begin
if (Length(fLineBuffer) > 0) then begin
memScreen.Lines.Add( fLineBuffer);
fLineBuffer := '';
end;
end;
end.

View file

@ -0,0 +1,219 @@
[EDSAC program, Initial Orders 2.
Calculates digits of pi by spigot algorithm.
Easily edited to calculate digits of e (see "if pi" and "if e" in comments).
Based on http://pi314.net/eng/goutte.php
See also https://www.cut-the-knot.org/Curriculum/Algorithms/SpigotForPi.shtml
Uses 17-bit values throughout.
Array index and counters are stored in the address field,
i.e. with the least significant bit in bit 1.
For integer arithmetic, the least significant bit is bit 0.
Variables don't need to be initialized at load time, so they overwrite
locations 6..12 of initial orders to save space.]
[6] P F [index into remainder array]
[7] P F [carry in the spigot algorithm]
[8] P F [negative count of digits]
[9] P F [pending digit, always < 9]
[10] P F [negative count of pending 9's]
[11] P F [9 or 0 in top 5 bits, for printing]
[12] P F [negative count of characters in current line]
[Array corresponding to Remainder row on http://pi314.net/eng/goutte.php]
T 53 K [refer to array via B parameter]
P 13 F [start array immediately after variables]
[Subroutine for short (17-bit) integer division.
Input: dividend at 4F, divisor at 5F.
Output: remainder at 4F, quotient at 5F.
Working locations 0F, 1F. 37 locations.]
T 987 K
GKA3FT34@A5FUFT35@A4FRDS35@G13@T1FA35@LDE4@T1FT5FA4FS35@G22@
T4FA5FA36@T5FT1FAFS35@E34@T1FA35@RDT35@A5FLDT5FE15@EFPFPD
T 845 K
G K
[Constants]
[Enter the editable numbers as addresses, e.g. P 100 F for 100.
Reducing the maximum array index will make the program take less time.
A maximum index of 831 (i.e. using all available memory) will give
252 correct digits of pi, or 2070 correct digits of e.]
[0] P 831 F [maximum array index <-- EDIT HERE, don't exceed 831]
[1] P 252 F [number of digits <-- EDIT HERE]
[2] P 72 F [digits per line <-- EDIT HERE]
[3] P D [short-value 1]
[4] P 5 F [short-value 10]
[5] J F [10*(2^12)]
[6] X F [add to T order to make V order]
[7] M F [used to convert T order to A order]
[8] # F [figures shift (for printer)]
[9] @ F [carriage return]
[10] & F [line feed]
[Main routine. Enter with acc = 0.]
[11] O 8 @ [set printer to figures; also used to print '9']
S 2 @ [load negative characters per line]
T 12 F [initialize character count]
S 1 @ [load negated number of digits]
T 8 F [initialize digit count]
T 10 F [clear negative count of 9's]
S 2 F [load -2 (any value < -1 would do)]
T 9 F [initialize digit buffer]
[Start algorithm: fill the remainder array with 2's (or 1's for e)
The code is a bit neater if we work backwards.]
A @ [maximum index]
[20] A 81 @ [make T order for array entry]
T 23 @ [plant in code]
[if pi] A 2 F [acc := 2]
[if e] [A 3 @] [acc := 1]
[23] T F [store in array entry]
A 23 @ [dec address in array]
S 2 F
S 81 @ [finished array?]
E 20 @ [loop back if not
Outer loop. Here for next digit.]
[28] T F [clear acc]
[Multiply remainder array by 10.
NB To preserve integer scaling, we need product times 2^16.]
H 5 @ [mult reg := 10*(2^12)]
A @ [acc := maximum index]
[31] A 81 @ [make T order for array entry]
U 37 @ [plant in code]
A 6 @ [convert to V order, same address]
T 35 @ [plant in code]
[35] V F [acc := array entry * 10*(2^12)]
L 4 F [shift to complete mult by 10*(2^16)]
[37] T F [store result in array]
A 37 @ [load T order]
S 2 F [dec address]
S 81 @ [test for done]
E 31 @ [loop back if not]
T F [clear acc]
T 7 F [clear carry]
A @ [acc := maximum index]
T 6 F [initialize array index]
[Inner loop to get next digit.
Work backwards through remainder array.]
[46] T F [clear acc]
A 6 F [load index]
A 81 @ [make T order for array entry]
U 61 @ [plant in code]
A 7 @ [convert to A order]
T 52 @ [plant in code]
[52] A F [load array element]
A 7 F [add carry from last time round loop]
T 4 F [sum to 4F for division routine]
A 6 F [acc := index as address = 2*(index as integer)]
[if pi] A 3 @ [plus 1]
[if e] [R D] [shift right, address --> integer]
T 5 F [to 5F for division routine (for e, 5F = index/2)]
[58] A 58 @ [call routine to divide 4F by 5F]
G 987 F
A 4 F [load remainder]
[61] T F [update element of remainder array]
[if pi: 4 orders]
H 5 F [mult reg := quotient]
V 6 F [multiply by index
NB need to shift 15 left to preserve integer scaling]
L F [shift 13 left]
L 1 F [shift 2 more left (for e, just use quotient)
[if e: 1 order, plus 3 no-ops to keep addresses the same]
[A 5 F] [load quotient]
[XF XF XF]
T 7 F [update carry for next time round loop]
A 6 F [load index]
S 2 F [decrement]
U 6 F [store back]
[We want to terminate after doing index = 1]
S 2 F [dec again]
E 46 @ [jump back if index >= 1]
[Treatment of index = 0 is different]
T F [clear acc]
A B [load rem{0)]
A 7 F [add carry]
T 4 F [sum to 4F for division routine]
A 4 @ [load 10]
T 5 F [to 5F for division routine]
[78] A 78 @ [call division routine]
G 987 F
A 4 F [load remainder]
[81] T B [store in rem{0}; also used to manufacture orders]
[82] A 82 @ [call subroutine to deal with quotient (clears acc)]
G 93 @
A 8 F [load negative digit count]
A 2 F [increment]
U 8 F [store back]
G 28 @ [if not yet 0, loop for next digit]
[Fake a zero digit to flush the last genuine digit(s)]
T 5 F [store fake digit 0 in 5F]
[89] A 89 @ [call subroutine to deal with digit]
G 93 @
O 8 @ [set figures: dummy character to flush print buffer]
Z F [stop]
[Subroutine to handle buffering and printing of digits.
Here with quotient from spigot algorithm still in 5F.
The quotient at 5F is usually the new decimal digit.
But the quotient can be 10, in which case we must treat it as 0
and ripple a carry through the previously-computed digits.
Hence the need for buffering.]
[93] A 3 F [make and plant return link]
T 130 @
A 5 F [load quotient]
S 4 @ [subtract 10]
E 105 @ [jump if quotient >= 10]
A 3 @ [add 1]
G 109 @ [jump if quotient < 9]
[Here if quotient = 9. Update count of 9's,
don't do anything with the buffer.]
T F [clear acc]
A 10 F [load negative count of 9's]
S 2 F [subtract 1]
T 10 F [update count]
E 130 @ [exit with acc = 0]
[Here if quotient >= 10. Take digit = quotient - 10,
and ripple a carry through the buffered digits.]
[105] T 5 F [store (quotient - 10) formed above]
T 11 F [store 0 to print '0' not '9']
A 3 @ [add 1 to buffered digit]
E 112 @ [join common code]
[Here if quotient < 9. Flush the stored digits.]
[109] T F [clear acc]
A 11 @ [load any O order (code for O is 9)]
T 11 F [store to print '9']
[112] A 9 F [load buffered digit, plus 1 if quotient >= 10]
G 118 @ [skip printing if buffer is empty]
L 1024 F [shift digits to top 5 bits]
T 1 F [store in 1F for printing]
[116] A 116 @ [call print routine]
G 131 @
[118] T F [clear acc]
A 5 F [load quotient (possibly modified as above)]
T 9 F [store in buffer]
[121] A 10 F [load negative count of 9's]
E 130 @ [if none, exit with acc = 0]
A 2 F [inc count]
T 10 F
A 11 F [load 9 (or 0 if there's a carry)]
T 1 F [to 1F for printing]
[127] A 127 @ [call print routine (clears acc)]
G 131 @
E 121 @ [jump back (always)]
[130] E F [return to caller]
[Subroutine to print character at 1F.
Also prints CR LF if necessary.]
[131] A 3 F [make and plant link for return]
T 141 @
A 12 F [load negative character count]
G 138 @ [jump if not end of line]
S 2 @ [reset character count]
O 9 @ [print CR LF]
O 10 @
[138] O 1 F [print character]
A 2 F [add 1]
T 12 F
[141] E F
E 11 Z [define entry point]
P F [acc = 0 on entry]

17
Task/Pi/Elixir/pi.elixir Normal file
View file

@ -0,0 +1,17 @@
defmodule Pi do
def calc, do: calc(1,0,1,1,3,3,0)
defp calc(q,r,t,k,n,l,c) when c==50 do
IO.write "\n"
calc(q,r,t,k,n,l,0)
end
defp calc(q,r,t,k,n,l,c) when (4*q + r - t) < n*t do
IO.write n
calc(q*10, 10*(r-n*t), t, k, div(10*(3*q+r), t) - 10*n, l, c+1)
end
defp calc(q,r,t,k,_n,l,c) do
calc(q*k, (2*q+r)*l, t*l, k+1, div(q*7*k+2+r*l, t*l), l+2, c)
end
end
Pi.calc

29
Task/Pi/Erlang/pi.erl Normal file
View file

@ -0,0 +1,29 @@
% Implemented by Arjun Sunel
-module(pi_calculation).
-export([main/0]).
main() ->
pi(1,0,1,1,3,3,0).
pi(Q,R,T,K,N,L,C) ->
if C=:=50 ->
io:format("\n"),
pi(Q,R,T,K,N,L,0) ;
true ->
if
(4*Q + R-T) < (N*T) ->
io:format("~p",[N]),
P = 10*(R-N*T),
pi(Q*10 , P, T , K , ((10*(3*Q+R)) div T)-10*N , L,C+1);
true ->
P = (2*Q+R)*L,
M = (Q*(7*K)+2+(R*L)) div (T*L),
H = L+2,
J =K+ 1,
pi(Q*K, P , T*L ,J,M,H,C)
end
end.

14
Task/Pi/F-Sharp/pi-1.fs Normal file
View file

@ -0,0 +1,14 @@
let rec g q r t k n l = seq {
if 4I*q+r-t < n*t
then
yield n
yield! (g (10I*q) (10I*(r-n*t)) t k ((10I*(3I*q+r))/t - 10I*n) l)
else
yield! (g (q*k) ((2I*q+r)*l) (t*l) (k+1I) ((q*(7I*k+2I)+r*l)/(t*l)) (l+2I))
}
let π = (g 1I 0I 1I 1I 3I 3I)
Seq.take 1 π |> Seq.iter (printf "%A.")
// 6 digits beginning at position 762 of π are '9'
Seq.take 767 (Seq.skip 1 π) |> Seq.iter (printf "%A")

3
Task/Pi/F-Sharp/pi-2.fs Normal file
View file

@ -0,0 +1,3 @@
// Generate Pi as above using unfold. Nigel Galloway: March 15th., 2022
let π()=Seq.unfold(fun(q,r,t,k,n,l)->Some(if 4I*q+r-t < n*t then(Some(int n),((10I*q),(10I*(r-n*t)),t,k,((10I*(3I*q+r))/t-10I*n),l)) else (None,((q*k),((2I*q+r)*l),(t*l),(k+1I),((q*(7I*k+2I)+r*l)/(t*l)),(l+2I)))))(1I,0I,1I,1I,3I,3I)|>Seq.choose id
π()|>Seq.take 767|>Seq.iter(printf "%d")

21
Task/Pi/Factor/pi.factor Normal file
View file

@ -0,0 +1,21 @@
USING: combinators.extras io kernel locals math prettyprint ;
IN: rosetta-code.pi
:: calc-pi-digits ( -- )
1 0 1 1 3 3 :> ( q! r! t! k! n! l! ) [
4 q * r + t - n t * < [
n pprint flush
r n t * - 10 *
3 q * r + 10 * t /i n 10 * - n! r!
q 10 * q!
] [
2 q * r + l *
7 k * q * 2 + r l * + t l * /i n! r!
k q * q!
t l * t!
l 2 + l!
k 1 + k!
] if
] forever ;
MAIN: calc-pi-digits

20
Task/Pi/Fortran/pi-1.f Normal file
View file

@ -0,0 +1,20 @@
program pi
implicit none
integer,dimension(3350) :: vect
integer,dimension(201) :: buffer
integer :: more,karray,num,k,l,n
more = 0
vect = 2
do n = 1,201
karray = 0
do l = 3350,1,-1
num = 100000*vect(l) + karray*l
karray = num/(2*l - 1)
vect(l) = num - karray*(2*l - 1)
end do
k = karray/100000
buffer(n) = more + k
more = karray - k*100000
end do
write (*,'(i2,"."/(1x,10i5.5))') buffer
end program pi

48
Task/Pi/Fortran/pi-2.f Normal file
View file

@ -0,0 +1,48 @@
!================================================
program pi_spigot_unbounded
!================================================
do
call print_next_pi_digit()
end do
contains
!------------------------------------------------
subroutine print_next_pi_digit()
!------------------------------------------------
use fmzm
type (im) :: q, r, t, k, n, l, nr
logical :: dot=.false., init=.false.
save :: q, r, t, k, n, l
if (.not.init) then
q=to_im(1)
r=to_im(0)
t=to_im(1)
k=to_im(1)
n=to_im(3)
l=to_im(3)
init=.true.
end if
if (4*q+r-t < n*t) then
write(6,fmt='(i1)',advance='no') to_int(n)
if (.not.dot) then
write(6,fmt='(a1)',advance='no') '.'
dot=.true.
end if
flush(6)
nr = 10 * ( r - n*t )
n = 10 * ( (3*q + r) / t - n )
q = 10 * q
r = nr
else
nr = (2*q + r) * l
n = ( (q * (7*k + 2) + r*l) / (t*l) )
q = q * k
t = t * l
l = l + 2
k = k + 1
r = nr
end if
end subroutine
end program

View file

@ -0,0 +1,54 @@
' version 05-07-2018
' compile with: fbc -s console
' unbounded spigot
' Ctrl-c to end program or close console window
#Include "gmp.bi"
Dim As UInteger num, ndigit, fp = Not 0
Dim As mpz_ptr q,r,t,k,n,l,tmp1,tmp2
q = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(q,1)
r = Allocate(Len(__Mpz_struct)) : Mpz_init(r)
t = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(t,1)
k = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(k,1)
n = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(n,3)
l = Allocate(Len(__Mpz_struct)) : Mpz_init_set_ui(l,3)
tmp1 = Allocate(Len(__Mpz_struct)) : Mpz_init(tmp1)
tmp2 = Allocate(Len(__Mpz_struct)) : Mpz_init(tmp2)
Do
mpz_mul_2exp(tmp1, q, 2)
mpz_add(tmp1,tmp1,r)
mpz_sub(tmp1,tmp1,t)
mpz_mul(tmp2, n, t)
If mpz_cmp(tmp1, tmp2) < 0 Then
Print mpz_get_ui(n); : ndigit += 1 : If ndigit Mod 50 = 0 Then Print " :";ndigit
If fp Then Print "."; : fp = Not fp : Print :ndigit = 0
mpz_sub(tmp1, r, tmp2)
mpz_mul_ui(tmp1, tmp1, 10)
mpz_mul_ui(tmp2, q, 3)
mpz_add(tmp2, tmp2, r)
mpz_mul_ui(tmp2, tmp2, 10)
mpz_set(r, tmp1)
mpz_mul_ui(tmp1, n, 10)
mpz_tdiv_q(tmp2, tmp2, t)
mpz_sub(n, tmp2, tmp1)
mpz_mul_ui(q, q, 10)
Else
mpz_mul(tmp2, r, l)
mpz_mul(tmp1, q, k)
mpz_mul_ui(tmp1, tmp1, 7)
mpz_add(tmp1, tmp1, tmp2)
mpz_mul_2exp(tmp2, q, 1)
mpz_add(tmp2, tmp2, r)
mpz_mul(tmp2, tmp2, l)
mpz_mul(t, t, l)
mpz_tdiv_q(tmp1, tmp1, t)
mpz_mul(q, q, k)
mpz_add_ui(k, k, 1)
mpz_add_ui(l, l, 2)
mpz_set(n, tmp1)
mpz_set(r, tmp2)
End If
Loop

20
Task/Pi/FunL/pi.funl Normal file
View file

@ -0,0 +1,20 @@
def compute_pi =
def g( q, r, t, k, n, l ) =
if 4*q + r - t < n*t
n # g( 10*q, 10*(r - n*t), t, k, (10*(3*q + r))\t - 10*n, l )
else
g( q*k, (2*q + r)*l, t*l, k + 1, (q*(7*k + 2) + r*l)\(t*l), l + 2 )
g( 1, 0, 1, 1, 3, 3 )
if _name_ == '-main-'
print( compute_pi().head() + '.' )
if args.isEmpty()
for d <- compute_pi().tail()
print( d )
else
for d <- compute_pi().tail().take( int(args(0)) )
print( d )
println()

View file

@ -0,0 +1,168 @@
_maxlong = 0x7fffffff
begin globals
long kf, ks
xref mf(_maxLong - 1) as long
xref ms(_maxLong - 1) as long
long cnt, n, temp, nd
long col, col1
long lloc, stor(50)
end globals
local mode
local fn FmtStr( nn as long, s as Str255 ) as Str255
long l
Str255 f
l = s[0]
select case
case ( nn => l ) : f = string$( nn-l, 32 ) + s
case ( -nn > l ) : f = s + string$( -nn-l, 32 )
case else : f = s
end select
end fn = f
local mode
local fn FmtInt( nn as long, s as Str255 ) as Str255
if ( left$( s, 1 ) = " " ) then s = mid$( s, 2 )
end fn = fn FmtStr( nn, s )
local fn yprint( m as long )
if ( cnt < n )
col++
if ( col == 11 )
col = 1
col1++
if ( col1 == 6 )
col1 = 0
print
print fn FmtInt( 4, str$( m mod 10) );
else
print fn FmtInt( 3, str$ (m mod 10) );
end if
else
print mid$( str$( m ), 2 ) ;
end if
end if
cnt++
end fn
local fn xprint( m as long )
long ii, wk, wk1
if ( m < 8 )
ii = 1
while ( ii <= lloc )
fn yprint( stor(ii) )
ii++
wend
lloc = 0
else
if ( m > 9 )
wk = m / 10
m = m mod 10
wk1 = lloc
while ( wk1 >= 1 )
wk += stor(wk1)
stor(wk1) = wk mod 10
wk = wk/10
wk1--
wend
end if
end if
lloc++
stor(lloc) = m
end fn
local mode
local fn shift( l1 as ^long, l2 as ^long, lp as long, lmod as long )
long k
if ( l2.nil& > 0 )
k = ( l2.nil& ) / lmod
else
k = -( -l2.nil& / lmod ) - 1
end if
l2.nil& = l2.nil& - k*lmod
l1.nil& = l1.nil& + k*lp
end fn
local fn Main( nDig as long )
long i
n = nDig
stor(0) = 0
mf = fn malloc( ( n + 10 ) * sizeof(long) )
if ( 0 == mf ) then stop "Out of memory"
ms = fn malloc( ( n + 10 ) * sizeof(long) )
if ( 0 == ms ) then stop "Out of memory"
print : printf @"Approximation of π to %ld digits", n
cnt = 0
kf = 25
ks = 57121
mf(1) = 1
i = 2
while ( i <= n )
mf(i) = -16
mf(i + 1) = 16
i += 2
wend
i = 1
while ( i <= n )
ms(i) = -4
ms(i + 1) = 4
i += 2
wend
print : print " 3.";
while ( cnt < n )
i = 0
i++
while ( i <= n - cnt )
mf(i) = mf(i) * 10
ms(i) = ms(i) * 10
i++
wend
i = ( n - cnt + 1 )
i--
while ( i >= 2 )
temp = 2 * i - 1
fn shift( @mf(i - 1), @mf(i), temp - 2, temp * kf )
fn shift( @ms(i - 1), @ms(i), temp - 2, temp * ks )
i--
wend
nd = 0
fn shift( @nd, @mf(1), 1, 5 )
fn shift( @nd, @ms(1), 1, 239 )
fn xprint( nd )
wend
print : print "Done"
fn free( ms )
fn free( mf )
end fn
window 1
CFTimeInterval t
t = fn CACurrentMediaTime
// Here we specify the number of decimal places
fn Main( 4000 )
print : printf @"Compute time: %.3f ms",(fn CACurrentMediaTime-t)*1000
HandleEvents

83
Task/Pi/Go/pi.go Normal file
View file

@ -0,0 +1,83 @@
package main
import (
"fmt"
"math/big"
)
type lft struct {
q,r,s,t big.Int
}
func (t *lft) extr(x *big.Int) *big.Rat {
var n, d big.Int
var r big.Rat
return r.SetFrac(
n.Add(n.Mul(&t.q, x), &t.r),
d.Add(d.Mul(&t.s, x), &t.t))
}
var three = big.NewInt(3)
var four = big.NewInt(4)
func (t *lft) next() *big.Int {
r := t.extr(three)
var f big.Int
return f.Div(r.Num(), r.Denom())
}
func (t *lft) safe(n *big.Int) bool {
r := t.extr(four)
var f big.Int
if n.Cmp(f.Div(r.Num(), r.Denom())) == 0 {
return true
}
return false
}
func (t *lft) comp(u *lft) *lft {
var r lft
var a, b big.Int
r.q.Add(a.Mul(&t.q, &u.q), b.Mul(&t.r, &u.s))
r.r.Add(a.Mul(&t.q, &u.r), b.Mul(&t.r, &u.t))
r.s.Add(a.Mul(&t.s, &u.q), b.Mul(&t.t, &u.s))
r.t.Add(a.Mul(&t.s, &u.r), b.Mul(&t.t, &u.t))
return &r
}
func (t *lft) prod(n *big.Int) *lft {
var r lft
r.q.SetInt64(10)
r.r.Mul(r.r.SetInt64(-10), n)
r.t.SetInt64(1)
return r.comp(t)
}
func main() {
// init z to unit
z := new(lft)
z.q.SetInt64(1)
z.t.SetInt64(1)
// lfts generator
var k int64
lfts := func() *lft {
k++
r := new(lft)
r.q.SetInt64(k)
r.r.SetInt64(4*k+2)
r.t.SetInt64(2*k+1)
return r
}
// stream
for {
y := z.next()
if z.safe(y) {
fmt.Print(y)
z = z.prod(y)
} else {
z = z.comp(lfts())
}
}
}

10
Task/Pi/Groovy/pi.groovy Normal file
View file

@ -0,0 +1,10 @@
BigInteger q = 1, r = 0, t = 1, k = 1, n = 3, l = 3
String nn
boolean first = true
while (true) {
(nn, first, q, r, t, k, n, l) = (4*q + r - t < n*t) \
? ["${n}${first?'.':''}", false, 10*q, 10*(r - n*t), t , k , 10*(3*q + r)/t - 10*n , l ] \
: ['' , first, q*k , (2*q + r)*l , t*l, k + 1, (q*(7*k + 2) + r*l)/(t*l), l + 2]
print nn
}

19
Task/Pi/Haskell/pi-1.hs Normal file
View file

@ -0,0 +1,19 @@
pi_ = g (1, 0, 1, 1, 3, 3)
where
g (q, r, t, k, n, l) =
if 4 * q + r - t < n * t
then n :
g
( 10 * q
, 10 * (r - n * t)
, t
, k
, div (10 * (3 * q + r)) t - 10 * n
, l)
else g
( q * k
, (2 * q + r) * l
, t * l
, k + 1
, div (q * (7 * k + 2) + r * l) (t * l)
, l + 2)

18
Task/Pi/Haskell/pi-2.hs Normal file
View file

@ -0,0 +1,18 @@
#!/usr/bin/runhaskell
import Control.Monad
import System.IO
pi_ = g(1,0,1,1,3,3) where
g (q,r,t,k,n,l) =
if 4*q+r-t < n*t
then n : g (10*q, 10*(r-n*t), t, k, div (10*(3*q+r)) t - 10*n, l)
else g (q*k, (2*q+r)*l, t*l, k+1, div (q*(7*k+2)+r*l) (t*l), l+2)
digs = insertPoint digs'
where insertPoint (x:xs) = x:'.':xs
digs' = map (head . show) pi_
main = do
hSetBuffering stdout $ BlockBuffering $ Just 80
forM_ digs putChar

3
Task/Pi/Haskell/pi-3.hs Normal file
View file

@ -0,0 +1,3 @@
piG3 = g(1,180,60,2) where
g(q,r,t,i) = let (u,y)=(3*(3*i+1)*(3*i+2),div(q*(27*i-12)+5*r)(5*t))
in y : g(10*q*i*(2*i-1),10*u*(q*(5*i-2)+r-y*t),t*u,i+1)

28
Task/Pi/Icon/pi.icon Normal file
View file

@ -0,0 +1,28 @@
procedure pi (q, r, t, k, n, l)
first := "yes"
repeat { # infinite loop
if (4*q+r-t < n*t) then {
suspend n
if (\first) := &null then suspend "."
# compute and update variables for next cycle
nr := 10*(r-n*t)
n := ((10*(3*q+r)) / t) - 10*n
q *:= 10
r := nr
} else {
# compute and update variables for next cycle
nr := (2*q+r)*l
nn := (q*(7*k+2)+r*l) / (t*l)
q *:= k
t *:= l
l +:= 2
k +:= 1
n := nn
r := nr
}
}
end
procedure main ()
every (writes (pi (1,0,1,1,3,3)))
end

View file

@ -0,0 +1,45 @@
10 REM PI CALCULATION WITH SPIGOT
100 N=100: REM MAX N=260 TO AVOID OVERFLOW
110 LEN=(10*N)/3
120 J=0:K=0:Q=0:NINES=0:PREDIGIT=0
125 DIM A(LEN)
130 REM VARIABLES FOR THE SUB
140 RESULT=0:I=0:X=0
200 REM MAIN
210 FOR J=1 TO LEN:A(J)=2: NEXT J
220 REM START WITH 222...
230 NINES=0
240 PREDIGIT=0
250 REM FIRST PREDIGIT =0
260 FOR J=1 TO N
270 I=N-J: GOSUB 1000:Q=RESULT
275 A(1)=Q MOD 10
280 Q=Q/10
290 IF Q=9 THEN NINES=NINES+1
300 IF Q=10 THEN GOSUB 800
310 IF (Q<>9) AND (Q<>10) THEN GOSUB 900
320 NEXT J
330 PRINT PREDIGIT
340 END
800 PRINT PREDIGIT+1;
805 IF NINES=0 THEN GOTO 820
810 FOR K=1 TO NINES: PRINT 0;: NEXT K
820 PREDIGIT=0:NINES=0
830 RETURN
900 PRINT PREDIGIT;
910 PREDIGIT=Q
920 IF NINES<>0 THEN GOSUB 950
930 RETURN
950 FOR K=1 TO NINES: PRINT 9;: NEXT K
960 NINES=0
970 RETURN
1000 I=I*10/3+16
1010 IF I>LEN THEN I=LEN
1020 RESULT=0
1030 REM REPEAT
1040 X=10*A(I)+RESULT*I
1050 RESULT=X/(2*I-1)
1060 A(I)=X MOD (2*I-1)
1070 I=I-1
1080 IF I>0 THEN GOTO 1040
1090 RETURN

7
Task/Pi/J/pi-1.j Normal file
View file

@ -0,0 +1,7 @@
pi=: 3 :0
echo"0 '3.1'
i=. 0
while. i=. i + 1 do.
echo -/ 1 10 * <.@o. 10x ^ 1 0 + i
end.
)

13
Task/Pi/J/pi-2.j Normal file
View file

@ -0,0 +1,13 @@
pi''
3
.
1
4
1
5
9
2
6
5
3
...

45
Task/Pi/Java/pi.java Normal file
View file

@ -0,0 +1,45 @@
import java.math.BigInteger ;
public class Pi {
final BigInteger TWO = BigInteger.valueOf(2) ;
final BigInteger THREE = BigInteger.valueOf(3) ;
final BigInteger FOUR = BigInteger.valueOf(4) ;
final BigInteger SEVEN = BigInteger.valueOf(7) ;
BigInteger q = BigInteger.ONE ;
BigInteger r = BigInteger.ZERO ;
BigInteger t = BigInteger.ONE ;
BigInteger k = BigInteger.ONE ;
BigInteger n = BigInteger.valueOf(3) ;
BigInteger l = BigInteger.valueOf(3) ;
public void calcPiDigits(){
BigInteger nn, nr ;
boolean first = true ;
while(true){
if(FOUR.multiply(q).add(r).subtract(t).compareTo(n.multiply(t)) == -1){
System.out.print(n) ;
if(first){System.out.print(".") ; first = false ;}
nr = BigInteger.TEN.multiply(r.subtract(n.multiply(t))) ;
n = BigInteger.TEN.multiply(THREE.multiply(q).add(r)).divide(t).subtract(BigInteger.TEN.multiply(n)) ;
q = q.multiply(BigInteger.TEN) ;
r = nr ;
System.out.flush() ;
}else{
nr = TWO.multiply(q).add(r).multiply(l) ;
nn = q.multiply((SEVEN.multiply(k))).add(TWO).add(r.multiply(l)).divide(t.multiply(l)) ;
q = q.multiply(k) ;
t = t.multiply(l) ;
l = l.add(TWO) ;
k = k.add(BigInteger.ONE) ;
n = nn ;
r = nr ;
}
}
}
public static void main(String[] args) {
Pi p = new Pi() ;
p.calcPiDigits() ;
}
}

View file

@ -0,0 +1,11 @@
let q = 1n, r = 180n, t = 60n, i = 2n;
for (;;) {
let y = (q*(27n*i-12n)+5n*r)/(5n*t);
let u = 3n*(3n*i+1n)*(3n*i+2n);
r = 10n*u*(q*(5n*i-2n)+r-y*t);
q = 10n*q*i*(2n*i-1n);
t = t*u;
i = i+1n;
process.stdout.write(y.toString());
if (i === 3n) { process.stdout.write('.'); }
}

View file

@ -0,0 +1,44 @@
<html><head><script src='https://rawgit.com/andyperlitch/jsbn/v1.1.0/index.js'></script></head>
<body style="width: 100%"><tt id="pi"></tt><tt>...</tt>
<script async defer>
function bi(n, b) { return new jsbn.BigInteger(n.toString(), b ? b : 10); };
var one=bi(1), two=bi(2), three=bi(3), four=bi(4), seven=bi(7), ten=bi(10);
function calcPi() {
var q=bi(1), r=bi(0), t=bi(1), k=bi(1), n=bi(3), l=bi(3);
var digit=0, firstrun=1;
var p=document.getElementById('pi');
function w(s) { p.appendChild(document.createTextNode(s));}
function continueCalcPi(q, r, t, k, n, l) {
while (true) {
if (q.multiply(four).add(r).subtract(t).compareTo(n.multiply(t)) < 0) {
w(n.toString());
if (digit==0 && firstrun==1) { w('.'); firstrun=0; };
digit = (digit+1) % 256;
var nr = (r.subtract(n.multiply(t))).multiply(ten);
n = (q.multiply(three).add(r)).multiply(ten).divide(t).subtract(n.multiply(ten));
q = q.multiply(ten);
r = nr;
if (digit%8==0) {
if (digit%64==0) {
p.appendChild(document.createElement('br'));
}
w(' ');
return setTimeout(function() { continueCalcPi(q, r, t, k, n, l); }, 50);
};
} else {
var nr = q.shiftLeft(1).add(r).multiply(l);
var nn = q.multiply(k).multiply(seven).add(two).add(r.multiply(l)).divide(t.multiply(l));
q = q.multiply(k);
t = t.multiply(l);
l = l.add(two);
k = k.add(one);
n = nn;
r = nr;
}
}
}
continueCalcPi(q, r, t, k, n, l);
}
calcPi();
</script>
</body></html>

View file

@ -0,0 +1,48 @@
<html>
<head>
</head>
<body style="width: 100%">
<tt id="pi"></tt>
<tt>...</tt>
<script async defer>
function calcPi() {
let q=1n, r=0n, t=1n, k=1n, n=3n, l=3n, nr, nn, digit=0, firstrun=1;
const p=document.getElementById('pi');
function w(s) { p.appendChild(document.createTextNode(s));}
// function continueCalcPi(q, r, t, k, n, l) { // (see note)
function continueCalcPi() {
while (true) {
if (q*4n+r-t < n*t) {
w(n.toString());
if (digit==0 && firstrun==1) { w('.'); firstrun=0; };
digit = (digit+1) % 256;
nr = (r-n*t)*10n;
n = (q*3n+r)*10n/t-n*10n;
q *= 10n;
r = nr;
if (digit%8==0) {
if (digit%64==0) {
p.appendChild(document.createElement('br'));
}
w('\xA0');
// return setTimeout(function() { continueCalcPi(q, r, t, k, n, l); }, 50);
return setTimeout(continueCalcPi, 50);
};
} else {
nr = (q*2n+r)*l;
nn = (q*k*7n+2n+r*l)/(t*l);
q *= k;
t *= l;
l += 2n;
k += 1n;
n = nn;
r = nr;
}
}
}
continueCalcPi(q, r, t, k, n, l);
}
calcPi();
</script>
</body>
</html>

View file

@ -0,0 +1,14 @@
var calcPi = function() {
var n = 20000;
var pi = 0;
for (var i = 0; i < n; i++) {
var temp = 4 / (i*2+1);
if (i % 2 == 0) {
pi += temp;
}
else {
pi -= temp;
}
}
return pi;
}

59
Task/Pi/Jq/pi-1.jq Normal file
View file

@ -0,0 +1,59 @@
# The Gibbons spigot, in the mold of the [[#Groovy]] and [[#Python]] programs shown on this page.
# The "bigint" functions needed are:
# long_minus long_add long_multiply long_div
def pi_spigot:
# S is the sixtuple:
# q r t k n l
# 0 1 2 3 4 5
def long_lt(x;y): if x == y then false else lessOrEqual(x;y) end;
def check:
long_lt(long_minus(long_add(long_multiply("4"; .[0]); .[1]) ; .[2]);
long_multiply(.[4]; .[2]));
# state: [d, S] where digit is null or a digit ready to be printed
def next:
.[1] as $S
| $S[0] as $q | $S[1] as $r | $S[2] as $t | $S[3] as $k | $S[4] as $n | $S[5] as $l
| if $S|check
then [$n,
[long_multiply("10"; $q),
long_multiply("10"; long_minus($r; long_multiply($n;$t))),
$t,
$k,
long_minus( long_div(long_multiply("10";long_add(long_multiply("3"; $q); $r)); $t );
long_multiply("10";$n)),
$l ]]
else [null,
[long_multiply($q;$k),
long_multiply( long_add(long_multiply("2";$q); $r); $l),
long_multiply($t;$l),
long_add($k; "1"),
long_div( long_add(long_multiply($q; long_add(long_multiply("7";$k); "2")) ; long_multiply($r;$l));
long_multiply($t;$l) ),
long_add($l; "2") ]]
end;
# Input: input to the filter "nextstate"
# Output: [count, space, digit] for successive digits produced by "nextstate"
def decorate( nextstate ):
# For efficiency it is important that the recursive
# function have arity 0 and be tail-recursive:
def count:
.[0] as $count
| .[1] as $state
| $state[0] as $value
| ($state[1] | map(length) | add) as $space
| (if $value then [$count, $space, $value] else empty end),
( [if $value then $count+1 else $count end, ($state | nextstate)] | count);
[0, .] | count;
# q=1, r=0, t=1, k=1, n=3, l=3
[null, ["1", "0", "1", "1", "3", "3"]] | decorate(next)
;
pi_spigot

305
Task/Pi/Jq/pi-2.jq Normal file
View file

@ -0,0 +1,305 @@
$ jq -M -n -c -f pi.bigint.jq
[0,9,"3"]
[1,14,"1"]
[2,29,"4"]
[3,36,"1"]
[4,51,"5"]
[5,69,"9"]
[6,80,"2"]
[7,95,"6"]
[8,115,"5"]
[9,125,"3"]
[10,142,"5"]
[11,167,"8"]
[12,181,"9"]
[13,197,"7"]
[14,226,"9"]
[15,245,"3"]
[16,263,"2"]
[17,276,"3"]
[18,300,"8"]
[19,320,"4"]
[20,350,"6"]
[21,363,"2"]
[22,383,"6"]
[23,408,"4"]
[24,429,"3"]
[25,442,"3"]
[26,475,"8"]
[27,502,"3"]
[28,510,"2"]
[29,531,"7"]
[30,563,"9"]
[31,611,"5"]
[32,613,"0"]
[33,628,"2"]
[34,649,"8"]
[35,676,"8"]
[36,711,"4"]
[37,720,"1"]
[38,748,"9"]
[39,783,"7"]
[40,792,"1"]
[41,814,"6"]
[42,849,"9"]
[43,870,"3"]
[44,886,"9"]
[45,923,"9"]
[46,939,"3"]
[47,967,"7"]
[48,1004,"5"]
[49,1041,"1"]
[50,1043,"0"]
[51,1059,"5"]
[52,1103,"8"]
[53,1133,"2"]
[54,1135,"0"]
[55,1165,"9"]
[56,1195,"7"]
[57,1212,"4"]
[58,1242,"9"]
[59,1273,"4"]
[60,1297,"4"]
[61,1313,"5"]
[62,1358,"9"]
[63,1375,"2"]
[64,1421,"3"]
[65,1423,"0"]
[66,1447,"7"]
[67,1493,"8"]
[68,1501,"1"]
[69,1533,"6"]
[70,1579,"4"]
[71,1581,"0"]
[72,1613,"6"]
[73,1630,"2"]
[74,1662,"8"]
[75,1701,"6"]
[76,1733,"2"]
[77,1735,"0"]
[78,1781,"8"]
[79,1792,"9"]
[80,1816,"9"]
[81,1849,"8"]
[82,1889,"6"]
[83,1898,"2"]
[84,1961,"8"]
[85,1963,"0"]
[86,1988,"3"]
[87,2013,"4"]
[88,2054,"8"]
[89,2071,"2"]
[90,2104,"5"]
[91,2129,"3"]
[92,2162,"4"]
[93,2195,"2"]
[94,2220,"1"]
[95,2230,"1"]
[96,2287,"7"]
[97,2289,"0"]
[98,2314,"6"]
[99,2340,"7"]
[100,2373,"9"]
[101,2414,"8"]
[102,2448,"2"]
[103,2458,"1"]
[104,2484,"4"]
[105,2534,"8"]
[106,2536,"0"]
[107,2569,"8"]
[108,2602,"6"]
[109,2645,"5"]
[110,2662,"1"]
[111,2696,"3"]
[112,2707,"2"]
[113,2756,"8"]
[114,2775,"2"]
[115,2825,"3"]
[116,2827,"0"]
[117,2853,"6"]
[118,2887,"6"]
[119,2914,"4"]
[120,2964,"7"]
[121,2966,"0"]
[122,3008,"9"]
[123,3027,"3"]
[124,3061,"8"]
[125,3088,"4"]
[126,3114,"4"]
[127,3165,"6"]
[128,3167,"0"]
[129,3202,"9"]
[130,3237,"5"]
[131,3287,"5"]
[132,3289,"0"]
[133,3316,"5"]
[134,3360,"8"]
[135,3387,"2"]
[136,3414,"2"]
[137,3456,"3"]
[138,3466,"1"]
[139,3510,"7"]
[140,3529,"2"]
[141,3564,"5"]
[142,3583,"3"]
[143,3610,"5"]
[144,3653,"9"]
[145,3697,"4"]
[146,3699,"0"]
[147,3752,"8"]
[148,3770,"1"]
[149,3789,"2"]
[150,3825,"8"]
[151,3852,"4"]
[152,3905,"8"]
[153,3933,"1"]
[154,3960,"1"]
[155,3970,"1"]
[156,4006,"7"]
[157,4033,"4"]
[158,4102,"5"]
[159,4104,"0"]
[160,4124,"2"]
[161,4159,"8"]
[162,4203,"4"]
[163,4248,"1"]
[164,4250,"0"]
[165,4269,"2"]
[166,4348,"7"]
[167,4350,"0"]
[168,4361,"1"]
[169,4405,"9"]
[170,4424,"3"]
[171,4460,"8"]
[172,4497,"5"]
[173,4542,"2"]
[174,4569,"1"]
[175,4605,"1"]
[176,4607,"0"]
[177,4644,"5"]
[178,4672,"5"]
[179,4691,"5"]
[180,4727,"9"]
[181,4764,"6"]
[182,4792,"4"]
[183,4820,"4"]
[184,4865,"6"]
[185,4893,"2"]
[186,4913,"2"]
[187,4949,"9"]
[188,4968,"4"]
[189,5005,"8"]
[190,5042,"9"]
[191,5070,"5"]
[192,5098,"4"]
[193,5144,"9"]
[194,5198,"3"]
[195,5200,"0"]
[196,5219,"3"]
[197,5266,"8"]
[198,5276,"1"]
[199,5313,"9"]
[200,5350,"6"]
[201,5387,"4"]
[202,5416,"4"]
[203,5435,"2"]
[204,5471,"8"]
[205,5526,"8"]
[206,5556,"1"]
[207,5558,"0"]
[208,5594,"9"]
[209,5632,"7"]
[210,5660,"5"]
[211,5689,"6"]
[212,5726,"6"]
[213,5746,"5"]
[214,5792,"9"]
[215,5821,"3"]
[216,5849,"3"]
[217,5887,"4"]
[218,5906,"4"]
[219,5961,"6"]
[220,5981,"1"]
[221,6002,"2"]
[222,6038,"8"]
[223,6068,"4"]
[224,6096,"7"]
[225,6134,"5"]
[226,6163,"6"]
[227,6191,"4"]
[228,6238,"8"]
[229,6267,"2"]
[230,6296,"3"]
[231,6316,"3"]
[232,6344,"7"]
[233,6383,"8"]
[234,6411,"6"]
[235,6440,"7"]
[236,6487,"8"]
[237,6525,"3"]
[238,6545,"1"]
[239,6574,"6"]
[240,6621,"5"]
[241,6641,"2"]
[242,6688,"7"]
[243,6717,"1"]
[244,6782,"2"]
[245,6784,"0"]
[246,6795,"1"]
[247,6852,"9"]
[248,6854,"0"]
[249,6910,"9"]
[250,6929,"1"]
[251,6959,"4"]
[252,6988,"5"]
[253,7027,"6"]
[254,7046,"4"]
[255,7085,"8"]
[256,7115,"5"]
[257,7153,"6"]
[258,7181,"6"]
[259,7229,"9"]
[260,7258,"2"]
[261,7288,"3"]
[262,7317,"4"]
[263,7383,"6"]
[264,7385,"0"]
[265,7415,"3"]
[266,7435,"4"]
[267,7474,"8"]
[268,7530,"6"]
[269,7569,"1"]
[270,7571,"0"]
[271,7609,"4"]
[272,7639,"5"]
[273,7678,"4"]
[274,7716,"3"]
[275,7736,"2"]
[276,7766,"6"]
[277,7805,"6"]
[278,7826,"4"]
[279,7873,"8"]
[280,7912,"2"]
[281,7933,"1"]
[282,7971,"3"]
[283,7991,"3"]
[284,8030,"9"]
[285,8060,"3"]
[286,8118,"6"]
[287,8120,"0"]
[288,8168,"7"]
[289,8189,"2"]
[290,8264,"6"]
[291,8266,"0"]
[292,8287,"2"]
[293,8317,"4"]
[294,8374,"9"]
[295,8395,"1"]
[296,8443,"4"]
[297,8464,"1"]
[298,8485,"2"]
[299,8524,"7"]
[300,8544,"3"]
[301,8593,"7"]
[302,8623,"2"]
...

11
Task/Pi/Julia/pi.julia Normal file
View file

@ -0,0 +1,11 @@
let prec = precision(BigFloat), spi = "", digit = 1
while true
if digit > lastindex(spi)
prec *= 2
setprecision(prec)
spi = string(big(π))
end
print(spi[digit])
digit += 1
end
end

45
Task/Pi/Kotlin/pi.kotlin Normal file
View file

@ -0,0 +1,45 @@
// version 1.1.2
import java.math.BigInteger
val ZERO = BigInteger.ZERO
val ONE = BigInteger.ONE
val TWO = BigInteger.valueOf(2L)
val THREE = BigInteger.valueOf(3L)
val FOUR = BigInteger.valueOf(4L)
val SEVEN = BigInteger.valueOf(7L)
val TEN = BigInteger.TEN
fun calcPi() {
var nn: BigInteger
var nr: BigInteger
var q = ONE
var r = ZERO
var t = ONE
var k = ONE
var n = THREE
var l = THREE
var first = true
while (true) {
if (FOUR * q + r - t < n * t) {
print(n)
if (first) { print ("."); first = false }
nr = TEN * (r - n * t)
n = TEN * (THREE * q + r) / t - TEN * n
q *= TEN
r = nr
}
else {
nr = (TWO * q + r) * l
nn = (q * SEVEN * k + TWO + r * l) / (t * l)
q *= k
t *= l
l += TWO
k += ONE
n = nn
r = nr
}
}
}
fun main(args: Array<String>) = calcPi()

View file

@ -0,0 +1,33 @@
{require lib_BN}
{def genpi
{def genpi.loop
{lambda {:n :pi :q :r :t :i :z}
{if {> :z :n}
then :pi
else {let { {:n :n} {:pi :pi} {:q :q} {:r :r} {:t :t} {:i :i} {:z :z}
{:digit {BN./ {BN.+ {BN.* {BN.- {BN.* :i 27} 12} :q}
{BN.* :r 5} }
{BN.* :t 5} } }
{:u {BN.* {BN.+ {BN.* :i 3} 1}
{BN.* 3 {BN.+ {BN.* :i 3} 2} } } }
} {genpi.loop :n
{BN.+ :pi :digit}
{BN.* {BN.* :q 1}
{BN.* :i {BN.- {BN.* :i 2} 1} }}
{BN.* {BN.* :u 1}
{BN.+ {BN.* :q {BN.- {BN.* :i 5} 2} }
{BN.- :r {BN.* :t :digit} }}}
{BN.* :t :u}
{BN.+ :i 1}
{+ :z 1}} }}}}
{lambda {:n}
{genpi.loop :n # 1 180 60 2 0} }}
-> genpi
We can generate π with 72 digits in about 500ms.
{BN.DEC 72}
-> 72 digits
{genpi 60}
-> 3.141592653589793238462643383279502884197169399375105820974944592307816406

View file

@ -0,0 +1,30 @@
{script
LAMBDATALK.DICT["spigot"] = function() {
function generateDigitsOfPi(max) {
var pi = "";
var z = 0;
var q = 1n;
var r = 180n;
var t = 60n;
var i = 2n;
while (z < max) {
var digit = ((i * 27n - 12n) * q + r * 5n) / (t * 5n);
pi += digit;
var u = (i * 3n + 1n) * 3n * (i * 3n + 2n);
r = u * 10n * (q * (i * 5n - 2n) + (r - t * digit));
q = q * 10n * i * (i * 2n - 1n);
i = i + 1n;
t = t * u;
z++;
}
return pi
}
var args = arguments[0].trim();
return generateDigitsOfPi( args );
};
}
We can generate 1000 digits of π in about 70ms
3.{W.rest {spigot 100}}
-> 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102701938521105559644622948954930381964428810975665933446128475648233786783165271201909145648566923460348610454326648213393607260249141273724587006606315588174881520920962829254091715364367892590360011330530548820466521384146951941511609433057270365759591953092186117381932611793105118548074462379962749567351885752724891227938183011949129833673362440656643086021394946395224737190702179860943702770539217176293176752384674818467669405132000568127145263560827785771342757789609173637178721468440901224953430146549585371050792279689258923542019956112129021960864034418159813629774771309960518707211349999998372978049951059731732816096318595024459455346908302642522308253344685035261931188171010003137838752886587533208381420617177669147303598253490428755468731159562863882353787593751957781857780532171226806613001927876611195909216420198

31
Task/Pi/Lasso/pi.lasso Normal file
View file

@ -0,0 +1,31 @@
#!/usr/bin/lasso9
define generatePi => {
yield currentCapture
local(r = array(), i, k, b, d, c = 0, x)
with i in generateSeries(1, 2800)
do #r->insert(2000)
with k in generateSeries(2800, 1, -14)
do {
#d = 0
#i = #k
while(true) => {
#d += #r->get(#i) * 10000
#b = 2 * #i - 1
#r->get(#i) = #d % #b
#d /= #b
#i--
!#i ? loop_abort
#d *= #i
}
#x = (#c + #d / 10000)
yield (#k == 2800 ? ((#x * 0.001)->asstring(-precision = 3)) | #x->asstring(-padding=4, -padChar='0'))
#c = #d % 10000
}
}
local(pi_digits) = generatePi
loop(200) => {
stdout(#pi_digits())
}

View file

@ -0,0 +1,35 @@
ndigits = 0
q = 1
r = 0
t = q
k = q
n = 3
L = n
first = 666 ' ANY non-zero =='true' in LB.
while ndigits <100
if ( 4 *q +r -t) <( n *t) then
print n;
ndigits =ndigits +1
if not( ndigits mod 40) then print: print " ";
if first =666 then first = 0: print ".";
nr =10 *( r -n *t)
n =int( ( (10 *( 3 *q +r)) /t) -10 *n)
q =q *10
r =nr
else
nr =( 2 *q +r) *L
nn =(q *( 7 *k +2) +r *L) /( t *L)
q =q *k
t =t *L
L =L +2
k =k +1
n =int( nn)
r =nr
end if
scan
wend
end

41
Task/Pi/Lua/pi.lua Normal file
View file

@ -0,0 +1,41 @@
a = {}
n = 1000
len = math.modf( 10 * n / 3 )
for j = 1, len do
a[j] = 2
end
nines = 0
predigit = 0
for j = 1, n do
q = 0
for i = len, 1, -1 do
x = 10 * a[i] + q * i
a[i] = math.fmod( x, 2 * i - 1 )
q = math.modf( x / ( 2 * i - 1 ) )
end
a[1] = math.fmod( q, 10 )
q = math.modf( q / 10 )
if q == 9 then
nines = nines + 1
else
if q == 10 then
io.write( predigit + 1 )
for k = 1, nines do
io.write(0)
end
predigit = 0
nines = 0
else
io.write( predigit )
predigit = q
if nines ~= 0 then
for k = 1, nines do
io.write( 9 )
end
nines = 0
end
end
end
end
print( predigit )

View file

@ -0,0 +1,95 @@
Module Checkpi {
Module FindPi(Digits){
Digits++
n=Int(3.32*Digits)
PlusOne=Lambda N=0% -> {
=N
N++
}
PlusTwo=Lambda N=1% -> {
=N
N+=2
}
Dim A(n)<<PlusOne(), B(n)<<PlusTwo()
Dim Ten(n), CarrierOver(n), Sum(n),Remainder(n)=2
OutPutDigits=Digits
Predigits=Stack
CallBack=lambda fl=true, Chars=0 (x)->{
Print x;
Chars++
If fl then Print "." : Print " "; : fl=false : Chars=0 : exit
If Chars=50 then {
Print
Print " ";
Chars=0
Refresh
} else.if (Chars mod 5)=0 then {
Print " ";
Refresh
}
\\ explicitly refresh output layer, using Fast ! mode of speed
}
Print "Pi=";
While Digits {
NextDigit(&CallBack, &Digits)
}
print
Refresh
Sub NextDigit(&f, &D)
CarrierOver=0
For k=n-1 to 1 {
Ten(k)=Remainder(k)*10%
CarrierOver(k)=CarrierOver
Sum(k)=Ten(k)+CarrierOver(k)
q=Sum(k) div B(k)
Remainder(k)=Sum(k)-B(k)*q
CarrierOver=A(k)*q
}
Ten(0)=Remainder(0)*10%
CarrierOver(0)=CarrierOver
Sum(0)=Ten(0)+CarrierOver(0)
q=Sum(0) div 10%
Remainder(0)=Sum(0)-10%*q
if q<>9 and q<>10 then {
Stack Predigits {
While not empty {
Call f(Number)
if D>0 then D--
If D=0 then flush ' empty stack
}
Push q
}
} else.if q=9 Then {
Stack Predigits { Data q }
} else {
Stack Predigits {
While not empty {
Call f((Number+1) mod 10)
if D>0 then D--
If D=0 then flush ' empty stack
}
Push 0
}
}
End Sub
}
\\ reduce time to share with OS
\\ Need explicitly use of refresh output layer (M2000 console)
\\ Slow for a screen refresh per statement and give more time to OS
Rem Set Slow
\\ Fast is normal screen refresh, per Refresh time, and give standard time to OS
Rem Set Fast
\\ Fast ! use Refresh for screen refresh, and give less time o OS than standard
\\ Esc key work when Refresh executed (and OS get little time)
Set Fast !
FindPi 4
FindPi 28
Print Pi ' pi in M2000 is Decimal type with 29 digits (1 plus 28 after dot, is same as FindPi 28)
Refresh
FindPi 50
}
Flush ' empty stack of values
CheckPi
List ' no variables exist
Modules ? ' current module exist
Stack ' Stack of values ' has to be empty, we didn't use current stack for values.

59
Task/Pi/MATLAB/pi.m Normal file
View file

@ -0,0 +1,59 @@
function pi_str = piSpigot(N)
% Return N digits of pi using Gibbons's first spigot algorithm.
% If N is omitted, the digits are printed ad infinitum.
% Uses the expansion
% pi = sum_{i=0} (i!)^2 2^{i+1} /(2i+1)!
% = 2 + 1/3 * ( 2 + 2/5 * (2 + 3/7 * ( 2 + 4/9 * ( ..... )))))
% = (2 + 1/3 *)(2 + 2/5 *)(2 + 3/7 *)...
% where the terms in the last expression represent Linear Fractional
% Transforms (LFTs).
%
% Requires the Variable Precision Integer (vpi) Toolbox
%
% Reference:
% "Unbounded Spigot Algorithms for the Digits of Pi" by J. Gibbons, 2004
% American Mathematical Monthly, vol. 113.
if nargin < 1
N = Inf;
lineLength = 50;
else
pi_str = repmat(' ',1,N);
end
q = vpi(1);
r = vpi(0);
t = vpi(1);
k = 1; % If printing more than 3E15 digits, use k = vpi(1);
i = 1;
first_digit = true;
while i <= N
threeQplusR = 3*q + r;
n = double(threeQplusR / t);
if q+threeQplusR < (n+1)*t
d = num2str(n);
if isinf(N)
fprintf(1,'%s', d);
if first_digit
fprintf(1,'.');
first_digit = false;
i = i+1;
end
if i == lineLength
fprintf(1,'\n');
i = 0;
end
else
pi_str(i) = d;
end
q = 10*q;
r = 10*(r-n*t);
i = i + 1;
else
t = (2*k+1)*t;
r = (4*k+2)*q + (2*k+1)*r;
q = k*q;
k = k + 1;
end
end
end

View file

@ -0,0 +1,3 @@
WriteString[$Output, "3."];
For[i = -1, True, i--,
WriteString[$Output, RealDigits[Pi, 10, 1, i][[1, 1]]]; Pause[.05]];

View file

@ -0,0 +1,28 @@
q = 1; r = 0; t = 1
k = 1; n = 3; l = 3
nn = null; nr = null
first = true
while true
if (((4 * q) + r) - t) < (n * t)
print n
if first
print "."
first = false
end
nr = int(10 * (r - (n * t)))
n = int((10 * ((3 * q) + r)) / t) - (10 * n)
q *= 10
r = nr
else
nr = int(((2 * q) + r) * l)
nn = int((((q * (7 * k)) + 2) + (r * l)) / (t * l))
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
end if
end while

View file

@ -0,0 +1,62 @@
/* NetRexx */
options replace format comments java crossref symbols binary
import java.math.BigInteger
runSample(arg)
return
-- 07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)07:11, 27 August 2022 (UTC)~~
method runSample(arg) private static
parse arg places .
if places = '' then places = -1
TWO = BigInteger.valueOf(2)
THREE = BigInteger.valueOf(3)
FOUR = BigInteger.valueOf(4)
SEVEN = BigInteger.valueOf(7)
q_ = BigInteger.ONE
r_ = BigInteger.ZERO
t_ = BigInteger.ONE
k_ = BigInteger.ONE
n_ = BigInteger.valueOf(3)
l_ = BigInteger.valueOf(3)
nn = BigInteger
nr = BigInteger
first = isTrue()
digitCt = 0
loop forever
if FOUR.multiply(q_).add(r_).subtract(t_).compareTo(n_.multiply(t_)) == -1 then do
digitCt = digitCt + 1
if places > 0 & digitCt - 1 > places then leave
say n_'\-'
if first then do
say '.\-'
first = isFalse()
end
nr = BigInteger.TEN.multiply(r_.subtract(n_.multiply(t_)))
n_ = BigInteger.TEN.multiply(THREE.multiply(q_).add(r_)).divide(t_).subtract(BigInteger.TEN.multiply(n_))
q_ = q_.multiply(BigInteger.TEN)
r_ = nr
end
else do
nr = TWO.multiply(q_).add(r_).multiply(l_)
nn = q_.multiply((SEVEN.multiply(k_))).add(TWO).add(r_.multiply(l_)).divide(t_.multiply(l_))
q_ = q_.multiply(k_)
t_ = t_.multiply(l_)
l_ = l_.add(TWO)
k_ = k_.add(BigInteger.ONE)
n_ = nn
r_ = nr
end
end
say
return
method isTrue() private static returns boolean
return (1 == 1)
method isFalse() private static returns boolean
return \isTrue()

46
Task/Pi/Nim/pi-1.nim Normal file
View file

@ -0,0 +1,46 @@
import bigints
var
tmp1, tmp2, tmp3, acc, k = initBigInt(0)
den, num, k2 = initBigInt(1)
proc extractDigit(): int32 =
if num > acc:
return -1
tmp3 = num shl 1 + num + acc
tmp1 = tmp3 div den
tmp2 = tmp3 mod den + num
if tmp2 >= den:
return -1
result = int32(tmp1.limbs[0])
proc eliminateDigit(d: int32) =
acc -= den * d
acc *= 10
num *= 10
proc nextTerm() =
k += 1
k2 += 2
acc += num shl 1
acc *= k2
den *= k2
num *= k
var i = 0
while true:
var d: int32 = -1
while d < 0:
nextTerm()
d = extractDigit()
stdout.write chr(ord('0') + d)
inc i
if i == 40:
echo ""
i = 0
eliminateDigit d

32
Task/Pi/Nim/pi-2.nim Normal file
View file

@ -0,0 +1,32 @@
import bignum
proc calcPi() =
var
q = newInt(1)
r = newInt(0)
t = newInt(1)
k = newInt(1)
n = newInt(3)
l = newInt(3)
var count = 0
while true:
if 4 * q + r - t < n * t:
stdout.write n
inc count
if count == 40: (echo ""; count = 0)
let nr = 10 * (r - n * t)
n = 10 * (3 * q + r) div t - 10 * n
q *= 10
r = nr
else:
let nr = (2 * q + r) * l
let nn = (7 * q * k + 2 + r * l) div (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
calcPi()

12
Task/Pi/OCaml/pi-1.ocaml Normal file
View file

@ -0,0 +1,12 @@
open Creal;;
let block = 100 in
let segment n =
let s = to_string pi (n*block) in
String.sub s ((n-1)*block) block in
let counter = ref 1 in
while true do
print_string (segment !counter);
flush stdout;
incr counter
done

43
Task/Pi/OCaml/pi-2.ocaml Normal file
View file

@ -0,0 +1,43 @@
open Num
(* series for: c*atan(1/k) *)
class atan_sum c k = object
val kk = k*/k
val mutable n = 0
val mutable kpow = k
val mutable pterm = c*/k
val mutable psum = Int 0
val mutable sum = c*/k
method next =
n <- n+1; kpow <- kpow*/kk;
let t = c*/kpow//(Int (2*n+1)) in
pterm <- if n mod 2 = 0 then t else minus_num t;
psum <- sum;
sum <- sum +/ pterm
method error = abs_num pterm
method bounds = if pterm </ Int 0 then (sum, psum) else (psum, sum)
end;;
let inv i = (Int 1)//(Int i) in
let t1 = new atan_sum (Int 16) (inv 5) in
let t2 = new atan_sum (Int (-4)) (inv 239) in
let base = Int 10 in
let npr = ref 0 in
let shift = ref (Int 1) in
let d_acc = inv 10000 in
let acc = ref d_acc in
let shown = ref (Int 0) in
while true do
while t1#error >/ !acc do t1#next done;
while t2#error >/ !acc do t2#next done;
let (lo1, hi1), (lo2, hi2) = t1#bounds, t2#bounds in
let digit x = int_of_num (floor_num ((x -/ !shown) */ !shift)) in
let d, d' = digit (lo1+/lo2), digit (hi1+/hi2) in
if d = d' then (
print_int d;
if !npr = 0 then print_char '.';
flush stdout;
shown := !shown +/ ((Int d) // !shift);
incr npr; shift := !shift */ base;
) else (acc := !acc */ d_acc);
done

20
Task/Pi/Oforth/pi.fth Normal file
View file

@ -0,0 +1,20 @@
: calcPiDigits
| q r t k n l |
1 ->q 0 ->r 1 ->t 1 ->k 3 ->n 3 -> l
while( true ) [
4 q * r + t - n t * < ifTrue: [
n print
r n t * - 10 *
3 q * r + 10 * t / n 10 * - ->n ->r
q 10 * ->q
]
else: [
2 q * r + l *
7 k * q * 2 + r l * + t l * / ->n ->r
k q * ->q
t l * ->t
l 2 + ->l
k 1+ ->k
]
] ;

24
Task/Pi/Ol/pi.ol Normal file
View file

@ -0,0 +1,24 @@
; 'numbers' is count of numbers or #false for eternal pleasure.
(define (pi numbers)
(let loop ((q 1) (r 0) (t 1) (k 1) (n 3) (l 3) (numbers numbers))
(unless (eq? numbers 0)
(if (< (- (+ (* 4 q) r) t) (* n t))
(begin
(display n)
(loop (* q 10)
(* 10 (- r (* n t)))
t
k
(- (div (* 10 (+ (* 3 q) r)) t) (* 10 n))
l
(if numbers (- numbers 1))))
(begin
(loop (* q k)
(* (+ (* 2 q) r) l)
(* t l)
(+ k 1)
(div (+ (* q (* 7 k)) 2 (* r l)) (* t l))
(+ l 2)
(if numbers (- numbers 1))))))))
(pi #false)

11
Task/Pi/PARI-GP/pi.parigp Normal file
View file

@ -0,0 +1,11 @@
pi()={
my(x=Pi,n=0,t);
print1("3.");
while(1,
if(n>=default(realprecision),
default(realprecision,default(realprecision)*2);
x=Pi
);
print1(floor(x*10^n++)%10)
)
};

42
Task/Pi/PL-I/pi.pli Normal file
View file

@ -0,0 +1,42 @@
/* Uses the algorithm of S. Rabinowicz and S. Wagon, "A Spigot Algorithm */
/* for the Digits of Pi". */
(subrg, fofl, size):
Pi_Spigot: procedure options (main); /* 21 January 2012. */
declare (n, len) fixed binary;
n = 1000;
len = 10*n / 3;
begin;
declare ( i, j, k, q, nines, predigit ) fixed binary;
declare x fixed binary (31);
declare a(len) fixed binary (31);
a = 2; /* Start with 2s */
nines, predigit = 0; /* First predigit is a 0 */
do j = 1 to n;
q = 0;
do i = len to 1 by -1; /* Work backwards */
x = 10*a(i) + q*i;
a(i) = mod (x, (2*i-1));
q = x / (2*i-1);
end;
a(1) = mod(q, 10); q = q / 10;
if q = 9 then nines = nines + 1;
else if q = 10 then
do;
put edit(predigit+1) (f(1));
do k = 1 to nines;
put edit ('0')(a(1)); /* zeros */
end;
predigit, nines = 0;
end;
else
do;
put edit(predigit) (f(1)); predigit = q;
do k = 1 to nines; put edit ('9')(a(1)); end;
nines = 0;
end;
end;
put edit(predigit) (f(1));
end; /* of begin block */
end Pi_Spigot;

64
Task/Pi/Pascal/pi.pas Normal file
View file

@ -0,0 +1,64 @@
Program Pi_Spigot;
const
n = 1000;
len = 10*n div 3;
var
j, k, q, nines, predigit: integer;
a: array[0..len] of longint;
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
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
write(predigit);
predigit := q;
if nines <> 0 then
begin
for k := 1 to nines do
write(9);
nines := 0
end
end
end;
writeln(predigit);
end.

41
Task/Pi/Perl/pi-1.pl Normal file
View file

@ -0,0 +1,41 @@
sub pistream {
my $digits = shift;
my(@out, @a);
my($b, $c, $d, $e, $f, $g, $i, $d4, $d3, $d2, $d1);
my $outi = 0;
$digits++;
$b = $d = $e = $g = $i = 0;
$f = 10000;
$c = 14 * (int($digits/4)+2);
@a = (20000000) x $c;
print "3.";
while (($b = $c -= 14) > 0 && $i < $digits) {
$d = $e = $d % $f;
while (--$b > 0) {
$d = $d * $b + $a[$b];
$g = ($b << 1) - 1;
$a[$b] = ($d % $g) * $f;
$d = int($d / $g);
}
$d4 = $e + int($d/$f);
if ($d4 > 9999) {
$d4 -= 10000;
$out[$i-1]++;
for ($b = $i-1; $out[$b] == 1; $b--) {
$out[$b] = 0;
$out[$b-1]++;
}
}
$d3 = int($d4/10);
$d2 = int($d3/10);
$d1 = int($d2/10);
$out[$i++] = $d1;
$out[$i++] = $d2-$d1*10;
$out[$i++] = $d3-$d2*10;
$out[$i++] = $d4-$d3*10;
print join "", @out[$i-15 .. $i-15+3] if $i >= 16;
}
# We've closed the spigot. Print the remainder without rounding.
print join "", @out[$i-15+4 .. $digits-2], "\n";
}

44
Task/Pi/Perl/pi-2.pl Normal file
View file

@ -0,0 +1,44 @@
use bigint try=>"GMP";
sub stream {
my ($next, $safe, $prod, $cons, $z, $x) = @_;
$x = $x->();
sub {
while (1) {
my $y = $next->($z);
if ($safe->($z, $y)) {
$z = $prod->($z, $y);
return $y;
} else {
$z = $cons->($z, $x->());
}
}
}
}
sub extr {
use integer;
my ($q, $r, $s, $t) = @{shift()};
my $x = shift;
($q * $x + $r) / ($s * $x + $t);
}
sub comp {
my ($q, $r, $s, $t) = @{shift()};
my ($u, $v, $w, $x) = @{shift()};
[$q * $u + $r * $w,
$q * $v + $r * $x,
$s * $u + $t * $w,
$s * $v + $t * $x];
}
my $pi_stream = stream
sub { extr shift, 3 },
sub { my ($z, $n) = @_; $n == extr $z, 4 },
sub { my ($z, $n) = @_; comp([10, -10*$n, 0, 1], $z) },
\&comp,
[1, 0, 0, 1],
sub { my $n = 0; sub { $n++; [$n, 4 * $n + 2, 0, 2 * $n + 1] } },
;
$|++;
print $pi_stream->(), '.';
print $pi_stream->() while 1;

54
Task/Pi/Perl/pi-3.pl Normal file
View file

@ -0,0 +1,54 @@
use bigint try=>"GMP";
# Pi/4 = 4 arctan 1/5 - arctan 1/239
# expanding it with Taylor series with what's probably the dumbest method
my ($ds, $ns) = (1, 0);
my ($n5, $d5) = (16 * (25 * 3 - 1), 3 * 5**3);
my ($n2, $d2) = (4 * (239 * 239 * 3 - 1), 3 * 239**3);
sub next_term {
my ($coef, $p) = @_[1, 2];
$_[0] /= ($p - 4) * ($p - 2);
$_[0] *= $p * ($p + 2) * $coef**4;
}
my $p2 = 5;
my $pow = 1;
$| = 1;
for (my $x = 5; ; $x += 4) {
($ns, $ds) = ($ns * $d5 + $n5 * $pow * $ds, $ds * $d5);
next_term($d5, 5, $x);
$n5 = 16 * (5 * 5 * ($x + 2) - $x);
while ($d5 > $d2) {
($ns, $ds) = ($ns * $d2 - $n2 * $pow * $ds, $ds * $d2);
$n2 = 4 * (239 * 239 * ($p2 + 2) - $p2);
next_term($d2, 239, $p2);
$p2 += 4;
}
my $ppow = 1;
while ($pow * $n5 * 5**4 < $d5 && $pow * $n2 * $n2 * 239**4 < $d2) {
$pow *= 10;
$ppow *= 10;
}
if ($ppow > 1) {
$ns *= $ppow;
#FIX? my $out = $ns->bdiv($ds); # bugged?
my $out = $ns / $ds;
$ns %= $ds;
$out = ("0" x (length($ppow) - length($out) - 1)) . $out;
print $out;
}
if ( $p2 % 20 == 1) {
my $g = Math::BigInt::bgcd($ds, $ns);
$ds /= $g;
$ns /= $g;
}
}

18
Task/Pi/Perl/pi-4.pl Normal file
View file

@ -0,0 +1,18 @@
use ntheory qw/Pi/;
say Pi(10000);
use Math::Pari qw/setprecision Pi/;
setprecision(10000);
say Pi;
use Math::MPFR;
my $pi = Math::MPFR->new();
Math::MPFR::Rmpfr_set_prec($pi, int(10000 * 3.322)+40);
Math::MPFR::Rmpfr_const_pi($pi, 0);
say Math::MPFR::Rmpfr_get_str($pi, 10, 10000, 0);
use Math::BigFloat try=>"GMP"; # Slow without Math::BigInt::GMP installed
say Math::BigFloat::bpi(10000); # For over ~2k digits, slower than AGM
use Math::Big qw/pi/; # Very slow
say pi(10000);

6
Task/Pi/Phix/pi-1.phix Normal file
View file

@ -0,0 +1,6 @@
(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">=</span><span style="color: #000000;">10000</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">=</span><span style="color: #000000;">8400</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span> <span style="color: #004080;">sequence</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">/</span><span style="color: #000000;">5</span><span style="color: #0000FF;">),</span><span style="color: #000000;">c</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">while</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">c</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span>
<span style="color: #000000;">b</span><span style="color: #0000FF;">=</span><span style="color: #000000;">c</span> <span style="color: #008080;">while</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">+=</span><span style="color: #000000;">f</span><span style="color: #0000FF;">[</span><span style="color: #000000;">b</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">a</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">-=</span><span style="color: #000000;">1</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">[</span><span style="color: #000000;">b</span><span style="color: #0000FF;">]=</span><span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">)</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">/</span><span style="color: #000000;">g</span><span style="color: #0000FF;">)</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">-=</span><span style="color: #000000;">1</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">-=</span><span style="color: #000000;">1</span> <span style="color: #008080;">if</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">d</span><span style="color: #0000FF;">*=</span><span style="color: #000000;">b</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span> <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;">"%04d"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">+</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">/</span><span style="color: #000000;">a</span><span style="color: #0000FF;">))</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">-=</span><span style="color: #000000;">14</span> <span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</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;">while</span>
<!--

35
Task/Pi/Phix/pi-2.phix Normal file
View file

@ -0,0 +1,35 @@
(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2400</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">len</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">*</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">len</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">nines</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">predigit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">q</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">len</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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">10</span><span style="color: #0000FF;">*</span><span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">q</span><span style="color: #0000FF;">*</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">*</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span>
<span style="color: #000000;">a</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">q</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">/</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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: #0000FF;">=</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">q</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">q</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">q</span><span style="color: #0000FF;">/</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">q</span><span style="color: #0000FF;">==</span><span style="color: #000000;">9</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">nines</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">nines</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span>
<span style="color: #008080;">else</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">nine</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'9'</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">q</span><span style="color: #0000FF;">==</span><span style="color: #000000;">10</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">predigit</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">q</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #000000;">nine</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'0'</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">predigit</span><span style="color: #0000FF;">+</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">nine</span><span style="color: #0000FF;">,</span><span style="color: #000000;">nines</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">predigit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">q</span>
<span style="color: #000000;">nines</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">predigit</span><span style="color: #0000FF;">+</span><span style="color: #008000;">'0'</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
<!--

22
Task/Pi/Picat/pi.picat Normal file
View file

@ -0,0 +1,22 @@
go =>
pi2(1,0,1,1,3,3,0),
nl.
pi2(Q,R,T,K,N,L,C) =>
if C == 50 then
nl,
pi2(Q,R,T,K,N,L,0)
else
if (4*Q + R-T) < (N*T) then
print(N),
P := 10*(R-N*T),
pi2(Q*10, P, T, K, ((10*(3*Q+R)) div T)-10*N, L,C+1)
else
P := (2*Q+R)*L,
M := (Q*(7*K)+2+(R*L)) div (T*L),
H := L+2,
J := K+ 1,
pi2(Q*K, P, T*L, J, M, H, C)
end
end,
nl.

21
Task/Pi/PicoLisp/pi.l Normal file
View file

@ -0,0 +1,21 @@
#!/usr/bin/picolisp /usr/lib/picolisp/lib.l
(de piDigit ()
(job '((Q . 1) (R . 0) (S . 1) (K . 1) (N . 3) (L . 3))
(while (>= (- (+ R (* 4 Q)) S) (* N S))
(mapc set '(Q R S K N L)
(list
(* Q K)
(* L (+ R (* 2 Q)))
(* S L)
(inc K)
(/ (+ (* Q (+ 2 (* 7 K))) (* R L)) (* S L))
(+ 2 L) ) ) )
(prog1 N
(let M (- (/ (* 10 (+ R (* 3 Q))) S) (* 10 N))
(setq Q (* 10 Q) R (* 10 (- R (* N S))) N M) ) ) ) )
(prin (piDigit) ".")
(loop
(prin (piDigit))
(flush) )

View file

@ -0,0 +1,57 @@
Function Get-Pi ( $Digits )
{
$Big = [bigint[]](0..10)
$ndigits = 0
$Output = ""
$q = $t = $k = $Big[1]
$r = $Big[0]
$l = $n = $Big[3]
# Calculate first digit
$nr = ( $Big[2] * $q + $r ) * $l
$nn = ( $q * ( $Big[7] * $k + $Big[2] ) + $r * $l ) / ( $t * $l )
$q *= $k
$t *= $l
$l += $Big[2]
$k = $k + $Big[1]
$n = $nn
$r = $nr
$Output += [string]$n + '.'
$ndigits++
$nr = $Big[10] * ( $r - $n * $t )
$n = ( ( $Big[10] * ( 3 * $q + $r ) ) / $t ) - 10 * $n
$q *= $Big[10]
$r = $nr
While ( $ndigits -lt $Digits )
{
While ( $ndigits % 100 -ne 0 -or -not $Output )
{
If ( $Big[4] * $q + $r - $t -lt $n * $t )
{
$Output += [string]$n
$ndigits++
$nr = $Big[10] * ( $r - $n * $t )
$n = ( ( $Big[10] * ( 3 * $q + $r ) ) / $t ) - 10 * $n
$q *= $Big[10]
$r = $nr
}
Else
{
$nr = ( $Big[2] * $q + $r ) * $l
$nn = ( $q * ( $Big[7] * $k + $Big[2] ) + $r * $l ) / ( $t * $l )
$q *= $k
$t *= $l
$l += $Big[2]
$k = $k + $Big[1]
$n = $nn
$r = $nr
}
}
$Output
$Output = ""
}
}

View file

@ -0,0 +1 @@
[math]::pi

View file

@ -0,0 +1,2 @@
.Net digits of pi
3.14159265358979

19
Task/Pi/Prolog/pi.pro Normal file
View file

@ -0,0 +1,19 @@
pi_spigot :-
pi(X),
forall(member(Y, X), write(Y)).
pi(OUT) :-
pi(1, 180, 60, 2, OUT).
pi(Q, R, T, I, OUT) :-
freeze(OUT,
( OUT = [Digit | OUT_]
-> U is 3 * (3 * I + 1) * (3 * I + 2),
Y is (Q * (27 * I - 12) + 5 * R) // (5 * T),
Digit is Y,
Q2 is 10 * Q * I * (2 * I - 1),
R2 is 10 * U * (Q * (5 * I - 2) + R - Y * T),
T2 is T * U,
I2 is I + 1,
pi(Q2, R2, T2, I2, OUT_)
; true)).

View file

@ -0,0 +1,40 @@
#SCALE = 10000
#ARRINT= 2000
Procedure Pi(Digits)
Protected First=#True, Text$
Protected Carry, i, j, sum
Dim Arr(Digits)
For i=0 To Digits
Arr(i)=#ARRINT
Next
i=Digits
While i>0
sum=0
j=i
While j>0
sum*j+#SCALE*arr(j)
Arr(j)=sum%(j*2-1)
sum/(j*2-1)
j-1
Wend
Text$ = RSet(Str(Carry+sum/#SCALE),4,"0")
If First
Text$ = ReplaceString(Text$,"3","3.")
First = #False
EndIf
Print(Text$)
Carry=sum%#SCALE
i-14
Wend
EndProcedure
If OpenConsole()
SetConsoleCtrlHandler_(?Ctrl,#True)
Pi(24*1024*1024)
EndIf
End
Ctrl:
PrintN(#CRLF$+"Ctrl-C was pressed")
End

26
Task/Pi/Python/pi.py Normal file
View file

@ -0,0 +1,26 @@
def calcPi():
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
while True:
if 4*q+r-t < n*t:
yield n
nr = 10*(r-n*t)
n = ((10*(3*q+r))//t)-10*n
q *= 10
r = nr
else:
nr = (2*q+r)*l
nn = (q*(7*k)+2+(r*l))//(t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
import sys
pi_digits = calcPi()
i = 0
for d in pi_digits:
sys.stdout.write(str(d))
i += 1
if i == 40: print(""); i = 0

View file

@ -0,0 +1,32 @@
[ immovable
]this[ share ]done[ ] is value ( --> x )
[ ]'[ replace ] is to ( x --> )
[ value 1 ] is Q ( --> x )
[ value 0 ] is R ( --> x )
[ value 1 ] is T ( --> x )
[ value 1 ] is K ( --> x )
[ value 3 ] is N ( --> x )
[ value 3 ] is L ( --> x )
[ value 0 ] is chcount ( --> x )
[ echo
chcount dup 79 =
if cr
1+ 80 mod to chcount ] is printch
[ 4 Q * R + T - N T * < iff
[ N printch
R N T * - 10 *
3 Q * R + 10 * T / N 10 * - to N to R
Q 10 * to Q ]
else
[ 2 Q * R + L *
7 K * Q * 2 + R L * + T L * / to N to R
K Q * to Q
T L * to T
L 2 + to L
K 1+ to K ]
chcount again ]

50
Task/Pi/R/pi.r Normal file
View file

@ -0,0 +1,50 @@
suppressMessages(library(gmp))
ONE <- as.bigz("1")
TWO <- as.bigz("2")
THREE <- as.bigz("3")
FOUR <- as.bigz("4")
SEVEN <- as.bigz("7")
TEN <- as.bigz("10")
q <- as.bigz("1")
r <- as.bigz("0")
t <- as.bigz("1")
k <- as.bigz("1")
n <- as.bigz("3")
l <- as.bigz("3")
char_printed <- 0
how_many <- 1000
first <- TRUE
while (how_many > 0) {
if ((FOUR * q + r - t) < (n * t)) {
if (char_printed == 80) {
cat("\n")
char_printed <- 0
}
how_many <- how_many - 1
char_printed <- char_printed + 1
cat(as.integer(n))
if (first) {
cat(".")
first <- FALSE
char_printed <- char_printed + 1
}
nr <- as.bigz(TEN * (r - n * t))
n <- as.bigz(((TEN * (THREE * q + r)) %/% t) - (TEN * n))
q <- as.bigz(q * TEN)
r <- as.bigz(nr)
} else {
nr <- as.bigz((TWO * q + r) * l)
nn <- as.bigz((q * (SEVEN * k + TWO) + r * l) %/% (t * l))
q <- as.bigz(q * k)
t <- as.bigz(t * l)
l <- as.bigz(l + TWO)
k <- as.bigz(k + ONE)
n <- as.bigz(nn)
r <- as.bigz(nr)
}
}
cat("\n")

29
Task/Pi/REXX/pi-1.rexx Normal file
View file

@ -0,0 +1,29 @@
/*REXX program spits out decimal digits of pi (one digit at a time) until Ctrl─Break.*/
parse arg digs oFID . /*obtain optional argument from the CL.*/
if digs=='' | digs=="," then digs= 1e6 /*Not specified? Then use the default.*/
if oFID=='' | oFID=="," then oFID='PI_SPIT.OUT' /* " " " " " " */
write= digs<0 /*if ODIGS is <0, also spit pi to file.*/
numeric digits abs(digs) + 4 /*with bigger digs, spitting is slower.*/
call time 'Reset' /*reset the wall─clock (elapsed) timer.*/
signal on halt /*───► HALT when Ctrl─Break is pressed.*/
spit= 0 /*the index of the spitted pi dec. digs*/
pi=0; v=5; vv=v*v; g=239; gg=g*g; s= 16 /*assign some values to some variables.*/
r= 4 /*calculate π with increasing accuracy */
do n=1 by 2 until old=pi; old= pi /*just calculate pi with odd integers*/
pi= pi + s / (n*v) - r / (n*g) /* ··· using John Machin's formula.*/
s= -s; r= -r; v= v * vv; g= g * gg /*compute some variables for shortcuts.*/
if n>3 then spit= spit + 1 /*maintain a lag for pi digits rounding*/
if spit<4 then iterate /*Not enough digs yet? Then don't show*/
$= substr(pi, spit-3, 1) /*lag behind the true pi calculation. */
call charout , $ /*write the spitted digits to the term.*/
if write then call charout oFID, $ /* " " " " " a file?*/
end /*n*/
$= substr(pi, spit - 2); L= length($) - 4 /*handle any residual decimal digits. */
if L>0 then do /*if any residual digits, then show 'em*/
call charout , substr($, 1, L) /*write to term. */
if write then call charout oFID, substr($, 1, L) /* " " file? */
end
say /*stick a fork in it, we're all done. */
exit: say; say n%2+1 'iterations took' format(time("Elapsed"),,2) 'seconds.'; exit 0
halt: say; say 'PI_SPIT halted via use of CtrlBreak.'; signal exit /*show iterations.*/

32
Task/Pi/REXX/pi-2.rexx Normal file
View file

@ -0,0 +1,32 @@
/*REXX program spits out decimal digits of pi (one digit at a time) until Ctrl-Break.*/
signal on halt /*───► HALT when Ctrl─Break is pressed.*/
parse arg digs oFID . /*obtain optional argument from the CL.*/
if digs=='' | digs=="," then digs= 300 /*Not specified? Then use the default.*/
if oFID=='' | oFID=="," then oFID='PI_SPIT2.OUT' /* " " " " " " */
numeric digits digs /*with bigger digs, spitting is slower.*/
q=1; r=0; t=1; k=1; n=3; L=3; z=0 /*define some REXX variables. */
dot=1 /*DOT≡a flag when a dot in pi is shown.*/
do until z==digs; qq= q+q /* qq is a fast version of: q*2 */
tn= t*n /* t*n is used twice (below). */
if qq+qq+r-t < tn then do; z= z+1 /* qq+qq is faster than qq*2 */
call charout , n
call charout oFID, n
if dot then do; dot=0; call charout , .
call charout oFID, .
end
nr= (r - tn) * 10
n = ((( (qq+q+r) * 10) / t) - n*10) %1
q = q*10
end
else do; nr= (qq+r) * L
tL= t*L
n = (q * (k*7 + 2) + r*L) / tL %1
q = q*k
t = tL
L = L+2
k = k+1
end /* %1≡fast way doing TRUNC of a number.*/
r=nr
end /*forever*/
exit /*stick a fork in it, we're all done. */
halt: say; say 'PI_SPIT2 halted via use of Ctrl-Break.'; exit

19
Task/Pi/Racket/pi-1.rkt Normal file
View file

@ -0,0 +1,19 @@
#lang racket
(require racket/generator)
(define pidig
(generator ()
(let loop ([q 1] [r 0] [t 1] [k 1] [n 3] [l 3])
(if (< (- (+ r (* 4 q)) t) (* n t))
(begin (yield n)
(loop (* q 10) (* 10 (- r (* n t))) t k
(- (quotient (* 10 (+ (* 3 q) r)) t) (* 10 n))
l))
(loop (* q k) (* (+ (* 2 q) r) l) (* t l) (+ 1 k)
(quotient (+ (* (+ 2 (* 7 k)) q) (* r l)) (* t l))
(+ l 2))))))
(for ([i (in-naturals)])
(display (pidig))
(when (zero? i) (display "." ))
(when (zero? (modulo i 80)) (newline)))

1
Task/Pi/Racket/pi-2.rkt Normal file
View file

@ -0,0 +1 @@
3.14159265358979323846264338327950288419716939937510...

33
Task/Pi/Raku/pi.raku Normal file
View file

@ -0,0 +1,33 @@
# based on http://www.mathpropress.com/stan/bibliography/spigot.pdf
sub stream(&next, &safe, &prod, &cons, $z is copy, @x) {
gather loop {
$z = safe($z, my $y = next($z)) ??
prod($z, take $y) !!
cons($z, @x[$++])
}
}
sub extr([$q, $r, $s, $t], $x) {
($q * $x + $r) div ($s * $x + $t)
}
sub comp([$q,$r,$s,$t], [$u,$v,$w,$x]) {
[$q * $u + $r * $w,
$q * $v + $r * $x,
$s * $u + $t * $w,
$s * $v + $t * $x]
}
my $pi :=
stream -> $z { extr($z, 3) },
-> $z, $n { $n == extr($z, 4) },
-> $z, $n { comp([10, -10*$n, 0, 1], $z) },
&comp,
<1 0 0 1>,
(1..*).map: { [$_, 4 * $_ + 2, 0, 2 * $_ + 1] }
for ^Inf -> $i {
print $pi[$i];
once print '.'
}

24
Task/Pi/Ruby/pi.rb Normal file
View file

@ -0,0 +1,24 @@
pi_digits = Enumerator.new do |y|
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
loop do
if 4*q+r-t < n*t
y << n
nr = 10*(r-n*t)
n = ((10*(3*q+r)) / t) - 10*n
q *= 10
r = nr
else
nr = (2*q+r) * l
nn = (q*(7*k+2)+r*l) / (t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
end
end
end
print pi_digits.next, "."
loop { print pi_digits.next }

37
Task/Pi/Rust/pi.rust Normal file
View file

@ -0,0 +1,37 @@
use num_bigint::BigInt;
fn main() {
calc_pi();
}
fn calc_pi() {
let mut q = BigInt::from(1);
let mut r = BigInt::from(0);
let mut t = BigInt::from(1);
let mut k = BigInt::from(1);
let mut n = BigInt::from(3);
let mut l = BigInt::from(3);
let mut first = true;
loop {
if &q * 4 + &r - &t < &n * &t {
print!("{}", n);
if first {
print!(".");
first = false;
}
let nr = (&r - &n * &t) * 10;
n = (&q * 3 + &r) * 10 / &t - &n * 10;
q *= 10;
r = nr;
} else {
let nr = (&q * 2 + &r) * &l;
let nn = (&q * &k * 7 + 2 + &r * &l) / (&t * &l);
q *= &k;
t *= &l;
l += 2;
k += 1;
n = nn;
r = nr;
}
}
}

36
Task/Pi/Scala/pi.scala Normal file
View file

@ -0,0 +1,36 @@
object Pi {
class PiIterator extends Iterable[BigInt] {
var r: BigInt = 0
var q, t, k: BigInt = 1
var n, l: BigInt = 3
def iterator: Iterator[BigInt] = new Iterator[BigInt] {
def hasNext = true
def next(): BigInt = {
while ((4 * q + r - t) >= (n * t)) {
val nr = (2 * q + r) * l
val nn = (q * (7 * k) + 2 + (r * l)) / (t * l)
q = q * k
t = t * l
l = l + 2
k = k + 1
n = nn
r = nr
}
val ret = n
val nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) / t) - (10 * n)
q = q * 10
r = nr
ret
}
}
}
def main(args: Array[String]): Unit = {
val it = new PiIterator
println("" + (it.head) + "." + (it.take(300).mkString))
}
}

30
Task/Pi/Scheme/pi.ss Normal file
View file

@ -0,0 +1,30 @@
(import (rnrs))
(define (calc-pi yield)
(let loop ((q 1) (r 0) (t 1) (k 1) (n 3) (l 3))
(if (< (- (+ (* 4 q) r) t) (* n t))
(begin
(yield n)
(loop (* q 10)
(* 10 (- r (* n t)))
t
k
(- (div (* 10 (+ (* 3 q) r)) t) (* 10 n))
l))
(begin
(loop (* q k)
(* (+ (* 2 q) r) l)
(* t l)
(+ k 1)
(div (+ (* q (* 7 k)) 2 (* r l)) (* t l))
(+ l 2))))))
(let ((i 0))
(calc-pi
(lambda (d)
(display d)
(set! i (+ i 1))
(if (= 40 i)
(begin
(newline)
(set! i 0))))))

39
Task/Pi/Seed7/pi.seed7 Normal file
View file

@ -0,0 +1,39 @@
$ include "seed7_05.s7i";
include "bigint.s7i";
const proc: main is func
local
var bigInteger: q is 1_;
var bigInteger: r is 0_;
var bigInteger: t is 1_;
var bigInteger: k is 1_;
var bigInteger: n is 3_;
var bigInteger: l is 3_;
var bigInteger: nn is 0_;
var bigInteger: nr is 0_;
var boolean: first is TRUE;
begin
while TRUE do
if 4_ * q + r - t < n * t then
write(n);
if first then
write(".");
first := FALSE;
end if;
nr := 10_ * (r - n * t);
n := 10_ * (3_ * q + r) div t - 10_ * n;
q *:= 10_;
r := nr;
flush(OUT);
else
nr := (2_ * q + r) * l;
nn := (q * (7_ * k + 2_) + r * l) div (t * l);
q *:= k;
t *:= l;
l +:= 2_;
incr(k);
n := nn;
r := nr;
end if;
end while;
end func;

Some files were not shown because too many files have changed in this diff Show more