/* * Prints all primes <= limit, where limit is an argument. * This uses the Sieve of Eratosthenes method. */ #include #include #define NUM_PER_LINE 10 typedef char bool; void sieve(bool isPrime[], int m) { int n, j, temp; for (n = 2; n <= m; n++) isPrime[n] = 1; for (n = 2; n * n <= m; n++) { if (isPrime[n]) { /* This for loop is a better way to do it than the while loop. */ /* for (k = n+n; k <= m; k += n) isPrime[k] = 0; */ j = 2; while (1) { temp = j * n; if (temp <= m) { isPrime[temp] = 0; j++; } else break; } } } } void printPrimes(bool *isPrime, int limit) { int n, count = 0; for (n = 2; n <= limit; n++) { if (isPrime[n]) { printf("%8d", n); if (++count == NUM_PER_LINE) { putchar('\n'); count = 0; } } } if (count > 0) putchar('\n'); } int main(int argc, char **argv) { int limit = atoi(argv[1]); /* bool isPrime[limit]; */ bool *isPrime = (bool *) malloc((limit+1) * sizeof(bool)); sieve(isPrime, limit); printPrimes(isPrime, limit); return 0; }