#include #include struct primes { unsigned long int num; struct primes *next; }; void dump( struct primes *p, unsigned long int n, unsigned long int count ); void add_prime( unsigned long int number, struct primes *p ); int try_prime( unsigned long int num, struct primes *p); #define runtime (finish - start) FILE *DUMPME; int main(int argc, char ** argv) { int result; struct primes *p; unsigned long int number, n = 0, count = 0; time_t start, finish; if (argc == 0) { printf ("Usage: %s [number]\n", argv[0]); } p = (struct primes *) malloc (sizeof(struct primes)); p -> num = 0; time(&start); printf ("Prime Crunching"); fflush(stdout); for (number = 1; number < 100000; number++) { result = try_prime(number, p); if (result) { fflush (stdout); count++; if (count == 1000) { printf ("."); count = 0; n++; } add_prime(number, p); } } time(&finish); DUMPME = fopen("prime.dump", "w"); printf ("\nDumping primes...\n"); dump(p, n, count); printf ("Numbers per second: %i\n", (number + 1) / runtime); printf ("Elapsed time (actually crunching): %i seconds\n", runtime); return 0; } void add_prime ( unsigned long int number, struct primes *p ) { if ( p -> num == 0 ) { p -> num = number; p -> next = (struct primes *) malloc (sizeof(struct primes)); p -> next -> num = 0; } else { add_prime( number, p -> next ); } } void dump( struct primes *p, unsigned long int n, unsigned long int count ) { for (; p -> num != 0; p = p -> next) { fprintf (DUMPME, "%i\n", p -> num); } free(p); p = NULL; printf ("Primes found: %i\n", (n * 1000) + count); fclose (DUMPME); } int try_prime( unsigned long int n, struct primes *p ) { if (n == 1) return 1; if ( p -> num > (n / 2) ) { return 1; } while (p -> num != 0) { if ( !(n % p -> num) && p -> num != 1 ) { return 0; } else { if (try_prime(n, p -> next)) { return 1; } else { return 0; } } } }