Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <math.h>
- #include <pthread.h>
- long long int perThreadOperations = 0;
- unsigned short gcd(unsigned short u, unsigned short v) {
- unsigned short shift = 0;
- if (u == 0) return v;
- if (v == 0) return u;
- while (((u | v) & 1) == 0) {
- shift++;
- u >>= 1;
- v >>= 1;
- }
- while ((u & 1) == 0)
- u >>= 1;
- do {
- while ((v & 1) == 0)
- v >>= 1;
- if (u > v) {
- unsigned short t = v; v = u; u = t;
- }
- v -= u;
- } while (v != 0);
- return u << shift;
- }
- void *genPairs(void * arg) {
- long long amount = *(long long int *)arg;
- long long coprimeCount = 0;
- srandom(time(NULL));
- int mngflFrct = amount*0.01;
- for(long long int a = 0 ; a < amount; ++a) {
- if(a % mngflFrct*5) printf("\r%5.2f%%", 100.0*((float) a/ (float) amount));
- unsigned short rand1 = random(), rand2 = random();
- if(gcd(rand1,rand2) == 1)
- coprimeCount++;
- }
- pthread_exit((void *)coprimeCount);
- }
- int main(int argc, char **argv) {
- if(argc != 3) {
- printf("Usage: RandomPi <Thread Count> <Pair Ammount>");
- return -4;
- }
- long long pairCount = atoll(argv[2]);
- char threadCount = atoi(argv[1]);
- printf("Threads: %d\r\n", threadCount);
- pthread_t threads[threadCount];
- long long mainCoprimeCounter = 0;
- //TODO - Implement a better way to split load between threads
- perThreadOperations = pairCount/threadCount;
- printf("Operations per single thread: %lld\r\n", perThreadOperations);
- for(int a = 0 ; a < threadCount ; ++a) {
- pthread_create(&threads[a], NULL, genPairs, &perThreadOperations);
- }
- for(int a = 0 ; a < threadCount ; ++a) {
- void *coprimeCount;
- pthread_join(threads[a], &coprimeCount);
- mainCoprimeCounter+=(long long)coprimeCount;
- }
- long long cofactors = perThreadOperations * threadCount - mainCoprimeCounter;
- printf("Statistics:\r\n\tCoprime pairs: %lld\r\n\tCofactor pairs: %lld\n\tPairs altogether: %lld\r\n", mainCoprimeCounter, cofactors, mainCoprimeCounter + cofactors);
- long double piApprox;
- if(mainCoprimeCounter != 0 && cofactors != 0) {
- long double coprimeShare = (long double)mainCoprimeCounter/((long double)pairCount);
- piApprox = sqrtl((long double)6/coprimeShare);
- printf("\r\n\tPi Approximation: %.15Lf", piApprox);
- } else {
- printf("One of the critical variables is zero!\r\nApproximating PI impossible.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement