How to resolve the algorithm Pi step by step in the FreeBASIC programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Pi step by step in the FreeBASIC programming language
Table of Contents
Problem Statement
Create a program to continually calculate and output the next decimal digit of
π
{\displaystyle \pi }
(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 3.14159265 ...
Note: this task is about calculating pi. For information on built-in pi constants see Real constants and functions.
Related Task Arithmetic-geometric mean/Calculate Pi
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Pi step by step in the FreeBASIC programming language
Source code in the freebasic programming language
' 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
You may also check:How to resolve the algorithm Long year step by step in the Julia programming language
You may also check:How to resolve the algorithm Arithmetic/Integer step by step in the Prolog programming language
You may also check:How to resolve the algorithm Extensible prime generator step by step in the Haskell programming language
You may also check:How to resolve the algorithm Array concatenation step by step in the Mercury programming language
You may also check:How to resolve the algorithm Probabilistic choice step by step in the FutureBasic programming language