I wrote a method that calculates PI (π) by using infinite series:
public static decimal NilakanthaGetPI(ulong n)//Nilakantha Series
{
decimal sum = 0;
decimal temp = 0;
decimal a = 2, b = 3, c = 4;
for (ulong i = 0; i < n; i++)
{
temp = 4 / (a * b * c);
sum += i % 2 == 0 ? temp : -temp;
a += 2; b += 2; c += 2;
}
return 3 + sum;
}
The method works fine till the number of iterations reaches a few billion which gives me a OverflowException which is logical because the value of temp is greater then the decimal type can hold. It came to my mind to use BigInteger but then I can't do the division temp = 4 / (a * b * c).With this method I can calculate the first 25 decimal digits of PI (decimal type can store 28 or 29 decimal digits). Is there a way to modify this method so that it can calculate more digits of PI?