Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Please help me with my program on vectors.

Status
Not open for further replies.

Lethal77X

Programmer
Apr 14, 2002
3
US
Hello, im having major problems getting my program to work. I have to list all the prime numbers from 1 to 1000. And I have to do this using a boolean vector. And i have to initialize all the numbers to true then go along and change them to false. Here's my code so far for the function that changes the true's to false's.

void TorF (vector<bool>& prime)
{
for (int current = 2; current < MAXSIZE; current++)
{
if (prime[current] = true)
{
for (int j = 2; j < MAXSIZE; current++)
{
if (current % j == 0)
prime[current] = false ;
}
}
}
}

...MAXSIZE = 1000
Yes i know this is very wrong. Do you have any pointers or tips for me...thanks alot
 
Hi,

By far the easiest way to do this is to first list all the number from 2 to 1000 in a 2D array and mark them as true.

The first prime is 2 so we keep it true and then mark all it's multiples as false.

The first number still true is 3 so again we keep it and mark all it's multiples false. Continue like this till you get to the end. You may be left with a number still hanging around but if that number is larger than the square root of 1000 you can mark it as false.

HTH



William
Software Engineer
ICQ No. 56047340
 
Hi, yes i got that far, and I've been playing around with the code in that function I posted. And i can't seem to make the code work, it still prints all 1000 numbers. The 2nd &quot;for&quot; statement is throwing me off. I know what to do, but i can't write it in code. Sorry, i'm very new to this.
 
I've had another look at your code from above and in your first if () you are doing an assigment not a comparison.

Change the = to an == and see how you get on.


William
Software Engineer
ICQ No. 56047340
 
OK, this is my revised function. It prints 2, then 3 5 7 all the way to 999. I see why its doing this but im absolutely clueless on how to make it print only the prime numbers. Help.

void TorF (vector<bool>& prime)
{
for (int current = 3; current < MAXSIZE; current++)
{
if (prime[current] == true)
{
for (int F = 2; current % F == 0; current++)
{
prime[current] = false ;

}
}
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top