using System.Diagnostics;
using System.Threading.Tasks;
static void Main(string[] args)
Console.Write("Enter the number of decimal places to calculate Pi: ");
if (int.TryParse(Console.ReadLine(), out int decimalPlaces))
Console.WriteLine("Please enter a non-negative number.");
Stopwatch stopwatch = new Stopwatch();
string pi = CalculatePi(decimalPlaces);
Console.WriteLine($"Pi to {decimalPlaces} decimal places: {pi}");
Console.WriteLine($"Time taken: {stopwatch.ElapsedMilliseconds} ms");
Console.WriteLine("Invalid input. Please enter a valid number.");
static string CalculatePi(int decimalPlaces)
ThreadLocal<BigInteger> localPi = new ThreadLocal<BigInteger>(() => 0, trackAllValues: true);
Parallel.For(0, decimalPlaces, i =>
BigInteger term1 = 4 / (8 * (BigInteger)i + 1);
BigInteger term2 = 2 / (8 * (BigInteger)i + 4);
BigInteger term3 = 1 / (8 * (BigInteger)i + 5);
BigInteger term4 = 1 / (8 * (BigInteger)i + 6);
BigInteger term = term1 - term2 - term3 - term4;
term *= BigInteger.Pow(sixteen, decimalPlaces - 1 - i);
foreach (var threadResult in localPi.Values)
string piString = pi.ToString();
return piString.Insert(1, ".");