Skip to content

Instantly share code, notes, and snippets.

@cesquivias
Created March 14, 2017 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cesquivias/dfd4aadb0f9648183af5220ec4f29d48 to your computer and use it in GitHub Desktop.
Save cesquivias/dfd4aadb0f9648183af5220ec4f29d48 to your computer and use it in GitHub Desktop.
Happy PI Day 2017
/*
* 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