#!/usr/bin/env python import sys import random import math """ Theory: The chance of two random integers being coprime is 6/pi**2 So try and generate pi using two parameters: * the maximum number (randint(1,N)) * the number of random pairs generated Ref: https://en.wikipedia.org/wiki/Coprime_integers Usage: ./random_vals_pi.py """ def calc_pi(max_rand, samples): coprime_count = 0 for _ in range(0, samples): if gcd(random.randint(1,max_rand), random.randint(1, max_rand)) == 1: coprime_count += 1 return math.sqrt( 6 / (coprime_count/float(samples)) ) def recursive_gcd(a,b): """ gcd calculated by Euclid's Algorithm https://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm """ if a == b: return a elif a > b: return gcd(a - b, b) else: return gcd(a, b - a) def gcd(a,b): """ gcd calculated by Euclid's Algorithm non-recursive to work on larger numbers https://en.wikipedia.org/wiki/Greatest_common_divisor#Using_Euclid.27s_algorithm """ while a != b: if a > b: a = a - b else: b = b - a return a if __name__ == "__main__": print( calc_pi(*[int(x) for x in sys.argv[1:3]]) )