Skip to content

Instantly share code, notes, and snippets.

@limzykenneth
Created March 14, 2017 06:38
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save limzykenneth/90cdca446d8e167fd12e7bac0043d3d4 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <math.h>
#include <stdint.h>
#include <random>
#include <chrono>
#include <stdlib.h>
using namespace std;
uint64_t gcd(uint64_t a, uint64_t b);
int main(int argc, char* argv[]){
if(argc > 2){
cerr<<"\n\tJust one option specifying number of iterations please. Leave blank for default (50,000,000).\n"<<endl;
return 1;
}
uint64_t iterations = 50000000;
if(argv[1]){
iterations = strtoul(argv[1], NULL, 0);
}
cout<<"Calculating PI..."<<endl;
unsigned seed1 = chrono::system_clock::now().time_since_epoch().count();
mt19937_64 g1 (seed1);
uint64_t i = 1;
uint64_t count = 0;
while(i < iterations){
uint64_t n1 = g1();
uint64_t n2 = g1();
if(gcd(n1, n2) == 1){
count++;
}
i++;
}
long double probability = (long double)count/(long double)iterations;
long double pi = sqrt(6/probability);
cout<<pi<<endl;
return 0;
}
uint64_t gcd(uint64_t a, uint64_t b) {
return b == 0 ? a : gcd(b, a % b);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment