#include #include #include #include /* Fifty million takes a while * For testing, you might want to reduce this quite a bit */ #define max 50000000 uint64_t primes[max] = {2}; /* You might want some global variables (mutexes, etc) out here */ void* prime_thread(void*){ /* Your code goes here! */ } /* Helper functions for test code near the end of main */ char check_prime(uint64_t num){ for(uint64_t idx = 0; idx < max && primes[idx] * primes[idx] <= num; idx++) if(!(num % primes[idx])) return 0; return 1; } char is_in_list(uint64_t num){ for(int64_t i = 0; i < max; i++) if(primes[i] == num) return 1; return 0; } /* Only needed if using quicksort */ int intcmp(const uint64_t *a, const uint64_t *b){ if(*a < *b) return -1; return *a > *b; } int main(int argc, char ** argv){ int threads = 1; if(argc > 1) threads = atoi(argv[1]); pthread_t handles[threads]; for(int i = 0; i < threads; i++) pthread_create(handles + i, 0, prime_thread, 0); for(int i = 0; i < threads; i++) pthread_join(handles[i], 0); /* Duplicate prime detection assumes the list is sorted * Uncomment this if your list isn't already sorted at this point */ // qsort(primes, max, sizeof(uint64_t), (int (*)(const void*, const void*))intcmp); printf("Middle 25 primes:\n"); for(uint64_t i = max/2; i < max/2 + 25; i++) printf("%lu\n", primes[i]); printf("Last 25 primes:\n"); for(uint64_t i = max - 25; i < max; i++) printf("%lu\n", primes[i]); /* These tests take a while, so they'll throw off any timing we do */ /* for(uint64_t i = 0; i < pcount - 1; i++) if(primes[i] == primes[i+1]) printf("Error: Duplicate prime recorded at index %d and %d\n", i, i); for(uint64_t i = 0; i < pcount - 1; i++) if(primes[i] > primes[i+1]) printf("Note: Out of order primes %lu and %lu\n", primes[i], primes[i+1]); for(uint64_t i = 0; i < pcount; i++) if(!check_prime(primes[i])) printf("Error: %lu at index %lu is not prime!\n", primes[i], i); for(uint64_t i = 2; i < primes[pcount-1]; i++) if(check_prime(i)) if(!is_in_list(i)) printf("Error: %lu is prime, but not in the list\n", i); */ return 0; }