Skip to content

Instantly share code, notes, and snippets.

@ThirdPartyNinjas
Last active March 12, 2018 20:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ThirdPartyNinjas/50919c47cb680f99e2f71f6a0198d784 to your computer and use it in GitHub Desktop.
Save ThirdPartyNinjas/50919c47cb680f99e2f71f6a0198d784 to your computer and use it in GitHub Desktop.
Calculating Pi from random numbers
using System;
namespace PiDay
{
// The probability of two random numbers to be coprime is P = 6 / Pi^2
// So let's generate a bunch of random numbers. Figure out how often they're coprime.
// Use that percentage as our probabilty and solve for Pi.
// Pi = sqrt(6 / P)
// For more info, watch the video where I stole the idea: https://youtu.be/RZBhSi_PwHU
class Program
{
static void Main(string[] args)
{
int pairsToTest = (args.Length == 1) ? int.Parse(args[0]) : 10000000;
int coprimeCount = 0;
Random r = new Random();
for (int i = 0; i < pairsToTest; i++)
{
int r1 = r.Next();
int r2 = r.Next();
if (Coprime(r1, r2))
{
coprimeCount++;
}
}
double percentCoprime = coprimeCount / (double)pairsToTest;
double calculatedPi = Math.Sqrt(6.0 / percentCoprime);
Console.WriteLine(string.Format("We calculated Pi to be: {0}", calculatedPi));
return;
}
public static int GetGCD(int a, int b)
{
while (b != 0)
{
var t = a % b;
a = b;
b = t;
}
return a;
}
public static bool Coprime(int a, int b)
{
if (((a | b) & 1) != 1)
return false;
return GetGCD(a, b) == 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment