/* prime.c - print prime numbers up to 1000 * To compile this program, type: gcc -o prime prime.c * Or you can put the "-o prime" after the "prime.c" */ #include #define YES 1 #define NO 0 /* For a number to be prime, there must be exactly one factor in the * range from 1 up to and including the square root of n. In other words, * from 2 to the sqrt(n), there cannot be any factors. */ int is_prime(int n) { int i; // Special case if (n == 1) return NO; for (i = 2; i*i <= n; ++i) if (n % i == 0) return NO; // If we get this far, we didn't find a divisor. That's good! return YES; } main() { int candidate, num_primes = 0; // We know the first prime number is 2. for (candidate = 2; candidate <= 1000; ++candidate) if (is_prime(candidate)) { printf("%d\n", candidate); ++ num_primes; } printf("I found %d prime numbers.\n", num_primes); }