### prime numbers

this program should display the prime numbers between 1 and 1000
I don't understand what is the problem.

 ``123456789101112131415161718192021222324252627282930313233343536`` ``````#include "stdafx.h" #include #include using namespace std; void prime(int); int _tmain(int argc, _TCHAR* argv[]) { int number; for(number=2;number<=1000;number++) { prime(number); } return 0; } void prime(int number) { for(int counter=2;counter<=(number/2);counter++); { if(number%counter!=0) { if(counter==(number/2)) { cout<

Last edited on
This line has a semicolon which should be removed:
`for(int counter=2;counter<=(number/2);counter++);`

The logic is also faulty. As written, it outputs a list of the odd numbers.
How can I fix it?
The test you have where you test the remainder is "not equal to zero" doesn't work. The usual problem is that you need every remainder to be non-zero. In your code, you filter the result so you are not checking all of them, only the case where counter = n/2, in other words you verify that it isn't divisible by 2.

You need to check that number cannot be exactly divided by any integer. So, if the remainder `number%counter` is equal to zero, the number is not prime. You could test that condition, if it's true, exit (return) from the function.

When the for-loop makes it all the way through to the end, you will know the number is prime. So put the cout statement after the end of the for loop.

Last edited on
thank you so much...
Topic archived. No new replies allowed.