Juggler_IN
Active Member
- Joined
- Nov 19, 2014
- Messages
- 358
- Office Version
- 2003 or older
- Platform
- Windows
I need help in fixing a C to VBA conversion code.
The code outputs the specified n-th digit of pi in base-10 (Decimal System) on the lines of the Bailey–Borwein–Plouffe formula which outputs the specified n-th digit of pi in base-16 (Hexadecimal System).
The converted, but not functional, VBA code and the reference C code are enclosed.
A fully-functional execution of the C code can be viewed at tio.run which is an online C compiler.
Cross-posted at: ExcelForum.com
An alternate code (which I don't want to pursue) cross-posted at: MrExcel.com
The code outputs the specified n-th digit of pi in base-10 (Decimal System) on the lines of the Bailey–Borwein–Plouffe formula which outputs the specified n-th digit of pi in base-16 (Hexadecimal System).
The converted, but not functional, VBA code and the reference C code are enclosed.
A fully-functional execution of the C code can be viewed at tio.run which is an online C compiler.
VBA Code:
Sub Main0()
' Expected output for i = 1 to 50 is 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4 6 2 6 4 3 3 8 3 2 7 9 4 0 2 8 8 4 1 9 7 1 6 9 3 9 9 3 7 5 1 0 5.
For i = 0 To 50
Debug.Print NthPi(i) & " ";
Next i
End Sub
Function NthPi(ByVal d As Integer) As Long
Dim ll, j, i
ll = Int((d + 2) * 10 / 3 + 2)
j = 0
i = 0
Dim x, r
ReDim x(0 To ll)
ReDim r(0 To ll)
Do
x(j) = 20
j = j + 1
Loop While j < ll
Dim c, n, e, p
p = 0
Do While i < d
j = 0
c = 0
Do
n = ll - j - 1
e = n * 2 + 1
r(j) = (x(j) + c) Mod e
c = (x(j) / e) * n
j = j + 1
Loop While j < ll
ll = ll - 1
p = x(ll) / 10
r(ll) = x(ll + 1) Mod 10
j = 0
Do
x(j) = r(j) * 10
j = j + 1
Loop While j < ll
i = i + 1
Loop
NthPi = p Mod 10
End Function
Code:
namespace System.Linq
{
class P
{
static void Main()
{
for (int i = 0; i <= 50; ++i)
{
Console.Write(NthPi(i));
}
Console.WriteLine();
Console.ReadLine();
}
static long NthPi(int d)
{
int l = (d+=2) * 10 / 3 + 2, j = 0, i = 0;
long[] x = new long[l], r = new long[l];
for (; j < l;)
x[j++] = 20;
long c, n, e, p = 0;
for (; i < d; ++i)
{
for (j = 0, c = 0; j < l; c = (x[j++] / e) * n)
{
n = l - j - 1;
e = n * 2 + 1;
r[j] = (x[j] += c) % e;
}
p = x[--l] / 10;
r[l] = x[l++] % 10;
for (j = 0; j < l;)
x[j] = r[j++] * 10;
}
return p % 10;
}
}
}
Cross-posted at: ExcelForum.com
An alternate code (which I don't want to pursue) cross-posted at: MrExcel.com