//
// EratosthenesSieve.cpp
//
// Anthony Dunk, 31/3/07
//
// This program uses the "Sieve of Eratosthenes" method to build a list of the prime
// numbers between 1 and N.
//
#include "stdafx.h"
int main(int argc, char* argv[])
{
//
// Find all primes between 1 and N
//
const int N = 1000;
// Define the sieve
bool prime[N+1];
// Flag all numbers as prime initially
int i,j,p;
for (i=1; i<=N; i++) prime[i]=true;
// Start with first prime, 2
p = 2;
while (true)
{
// Eliminate all factors of this prime
j=2*p;
while (j<=N)
{
prime[j]=false; // Flag this number as non-prime
j=j+p;
}
// Find the next prime
bool next_prime_found = false;
for (i=p+1; i<=N; i++)
{
if (prime[i])
{
p = i;
next_prime_found = true;
break;
}
}
// Exit loop if all prime factors have been eliminated
if (!next_prime_found) break;
}
// Display the primes and count them
printf("Prime numbers between 1 and %d:\n\n",N);
int count = 0;
for (i=2; i<=N; i++)
{
if (prime[i])
{
printf("%4d ",i);
count++;
}
}
printf("\n\n");
printf("%d primes\n\n",count);
return 0;
}
|