/* * Celebrate Pi day in C. * * See https://www.youtube.com/watch?v=RZBhSi_PwHU to watch Matt Parker * do it the hard way. * * See https://www.youtube.com/watch?v=LFwSIdLSosI for a more in-depth * explanation of why this works. */ #include #include #include #include #include #define NR_PAIRS 1000000 static unsigned int gcd(unsigned int a, unsigned int b) { unsigned int tmp; while (b != 0) { tmp = b; b = a % b; a = tmp; } return a; } static bool coprimes(unsigned int a, unsigned int b) { return (gcd(a, b) == 1); } int main(int argc, char **argv) { unsigned int i, total; double pi; srand(time(NULL)); for (i = 0, total = 0; i < NR_PAIRS; i++) { if (coprimes(rand(), rand())) { total++; } } /* Division by zero ? What's the problem ? */ pi = sqrt(6. * NR_PAIRS / total); printf("%f\n", pi); }