Files
print_hej/csharp/.dotnet_temp/Program.cs
T
Ein Anderssono 54d2fecee0 Initial commit: Pi calculation benchmark with 34 languages
- Added implementations for: bash, brainfuck, c, cpp, crystal, csharp, d, dart, elixir, erlang, fortran, go, haskell, java, javascript, julia, kotlin, objective-c, scala, typescript, lua, nim, odin, perl, php, python, r, ruby, rust, swift, zig, assembly, vimscript, wolfram
- All implementations use Machin's formula: π/4 = 4*arctan(1/5) - arctan(1/239)
- Build system with ./build.sh, test system with ./test.sh
- Performance testing with ./run_all.sh
- Comprehensive README.md explaining performance differences
- Test framework verifies correctness against known π values
2026-04-23 00:26:18 +02:00

66 lines
1.7 KiB
C#

using System;
using System.Numerics;
class Program
{
static void Main(string[] args)
{
int decimals = 100;
if (args.Length > 0)
{
if (!int.TryParse(args[0], out decimals) || decimals <= 0)
decimals = 100;
}
BigInteger pi = CalculatePi(decimals);
Console.WriteLine(FormatPi(pi, decimals));
}
// Calculate arctan(1/x) using Taylor series
static BigInteger Arctan(int x, int decimals)
{
BigInteger scale = BigInteger.Pow(10, decimals + 10);
BigInteger xBig = new BigInteger(x);
BigInteger xSquared = xBig * xBig;
BigInteger result = BigInteger.Zero;
BigInteger term = scale / xBig;
int n = 0;
while (term != 0 && n < decimals * 3)
{
BigInteger divisor = new BigInteger(2 * n + 1);
BigInteger contrib = term / divisor;
if (n % 2 == 0)
result += contrib;
else
result -= contrib;
term /= xSquared;
n++;
if (n > decimals * 2) break;
}
return result;
}
// Calculate pi using Machin's formula
static BigInteger CalculatePi(int decimals)
{
BigInteger atan1_5 = Arctan(5, decimals);
BigInteger atan1_239 = Arctan(239, decimals);
return 16 * atan1_5 - 4 * atan1_239;
}
// Format pi with decimal point
static string FormatPi(BigInteger pi, int decimals)
{
string piStr = pi.ToString();
while (piStr.Length < decimals + 10)
piStr = "0" + piStr;
return "3." + piStr.Substring(1, decimals);
}
}