Prime Number program

Hi, I've a doubt about a program taken on a guide. It find all prime number from 1 to 100.

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
int x, y;
bool insprime;

for(x=1; x<=100; x++) {

insprime = true;

for(y=2; y<=x/2; y++)
if((x%y)==0) insprime = false;

if(insprime)
cout << x << " is prime. \n";
}
cout << '\n';
system("PAUSE");

return 0;
}

Everything works correct. But if I do the expression with my hand, if x is 1 and y is 2 ok, but if x is 2 and y is 2 because y<=2/2, so y doesn't become 3, the result should be 2%2 == 0 so insprime = false. Instead this program shows me number 2 too as a prime number. Sorry for my english but I'm italian xD. Anyway anyone can made me clear this "error"?
In doubt if I'm crazy or not I verified that my calculates were right with a program that shows me the modulus.
Last edited on
2 is a prime number but 1 is not prime. HTH

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
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
	int x, y;
	bool insprime;

	for(x=2; x<=100; x++) {

	insprime = true;

		for(y=2; y<=x/2; y++)
			if((x%y)==0) insprime = false;

		if(insprime)
		cout << x << " is prime. \n";
	}
	cout << "\n";
	//system("PAUSE");

	return 0;
}
when x = 2, y = 2, y<=x/2 (2<=1) returns false so program never enters that for loop.
Note that this loop only has one statement in it. This would be easier to notice, if your code was properly indented. insprime was set to be true in a line above so it remains true in the line below.

by the way, 1 is not prime...
closed account (D80DSL3A)
Right. Thefor(y=2; y<=x/2; y++) executes no iterations until x >= 4. I think your confusion came from expecting if((x%y)==0) insprime = false; to execute for x=2, which it will not do.
Ok thanks you all, my apologies, i told 1 was a prime because in italian 1st = "primo", I do this mistake since I was a child :(
Topic archived. No new replies allowed.