// Assignment: sieve.cpp
// Purpose: To write the most efficient program
// that outputs prime numbers.
#include<iostream.h>
#include<iomanip.h>
#include<math.h>
// declare constant MAX_NUMBER to be the # of arrays.
const MAX_NUMBER = 1000;
// declare array primes.
bool primes[MAX_NUMBER];
// function prototypes
void initializeArray();
void findMultiples();
void printSubscripts();
int main()
{
// call to functions
initializeArray();
findMultiples();
printSubscripts();
return 0;
}
//*****************************************************
// function initializeArray
//
// Purpose: to initialize the Aray
//
// Input: none
// Output: none
void initializeArray()
{
// start from index 2, ignoring 1 and 0
for(int index = 0; index < MAX_NUMBER; index++)
primes[index] = true;
primes[0] = false;
primes[1] = false;
}
//*****************************************************
// function findMultiples
//
// Purpose: assign false to multiples of prime numbers
//
// Input: none
// Output: none
void findMultiples()
{
int steps = 0;
// for loop, starting the primes at 2, incrementing every loop
for(int index = 2; index < sqrt(MAX_NUMBER); index++)
// if true, then continue
if(primes[index] == true)
// all multiples of primes are assigned false
for(int multiplier = 2; multiplier * index < MAX_NUMBER; multiplier++)
{
primes[multiplier * index] = false;
steps++;
}
cout << "Number of steps are : " << steps << endl;
}
//*****************************************************
// function printSubscripts
//
// Purpose: print prime numbers to console
//
// Input: none
// Output: prime numbers
void printSubscripts()
{
cout << "The prime numbers from 1 to " << MAX_NUMBER-1 << " are:\n" << endl;
// output primes starting from primes[2]
for(int index = 0; index < MAX_NUMBER; index++)
{
if(primes[index])
// a "tab" between every prime number.
cout << index << "\t";
}
cout << endl;
}
Some of the comments may not be correct because I'm just learning programming
I'm using Visual C++ 6.0.
Thanks,
Craig
Edited by Csshih, 14 February 2008 - 06:42 PM.















