Hello,

*'m trying to complete a homework assignment using a bool type array to find the prime numbers from 2 to 1000 based on the sieve of Eratosthenes. The code I've included below will find the prime numbers, but skips the first 11 primes (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, and 31). I can't see what I'm doing wrong. Can anyone help? Any help would be greatly appreciated.. Thanks.

Sam*

`#include <iostream>

# include <iomanip>

using namespace std;

int main()
{
const int arraySize = 1000;
bool arrayPrime [ arraySize ];

``````//initialize the array elements to true
for( int i = 0; i < arraySize; i++ )
{
arrayPrime[i] = true;
}//end initialization

//determine prime elements
for( int i = 2; i < arraySize; i++ )
{
for(int j = 2; j < arraySize; j++)
{

if( j > i  && arrayPrime[j] == true)
{
if(j%i == 0)
{
arrayPrime[j] = false;
arrayPrime[i] = arrayPrime[j];
}//end if
}//end if

}//end second for
}//end first for

//print all prime elements of the array
cout << "All prime numbers from 0 to " << arraySize << "\n\n" << endl;
for(int i = 0; i < arraySize; i++)
{
if(arrayPrime[i] ==true)
{
cout << "arrayPrime[" << i << "]" <<
"equals: " << arrayPrime[i] << endl;
}//end if
}//end for
``````

cin.ignore(1);
}//endmain
`

2
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by samiam5976

What's the purpose of line 18? Take it out and see what happens.

All of the elements of arrayPrime[] were initialized to "true". If the array element ( i.e., arrayPrime[ 4 ]) is not a prime number, the content of the element is changed from "true" to "false".

I took it out and it worked. Thanks for the help.