Created
March 14, 2017 19:54
-
-
Save cesquivias/dfd4aadb0f9648183af5220ec4f29d48 to your computer and use it in GitHub Desktop.
Happy PI Day 2017
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Happy PI Day '17 | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <math.h> | |
#include <time.h> | |
const int COUNT = 1000000; | |
const int MAX = 1000000; | |
int gcd(int a, int b) { | |
int temp; | |
while (b != 0) | |
{ | |
temp = a % b; | |
a = b; | |
b = temp; | |
} | |
return a; | |
} | |
int randint(int limit) { | |
int divisor = RAND_MAX/(limit+1); | |
int retval; | |
do { | |
retval = rand() / divisor; | |
} while (retval > limit); | |
return retval + 1; | |
} | |
int main() { | |
srand(time(NULL)); | |
int coprimes = 0; | |
for (int i=0; i<COUNT; i++) { | |
if (gcd(randint(MAX), randint(MAX)) == 1) { | |
coprimes++; | |
} | |
} | |
double x = ((double) coprimes) / COUNT; | |
double pi = sqrt(6 / x); | |
printf("%f\n", pi); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment