prime numbers

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



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include "stdafx.h"
#include<iostream>
#include<cmath>

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<<number<<",";
			}
		}
		
	}

}



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.