i wrote this code and it works but now i'm wondering how it works?

so i'm trying to find the primary numbers under 500 and this code works but I don't understand why when looking at it because when i in the for loop is lets say 11, wouldn't the if statement i%11 != 0 be false and therefore not print out i? but it does print 11 (which is good cuz its a primary number) but i dont see how or why this works? can someone explain?



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

using namespace std;

int main()
{
	for(int i = 3; i < 8000; i++)
	{
		if(i%2 != 0)
		{
			if(i < 9)
				cout << i << ' ';
			else if(i >= 9 && i < 500)
				if(i%3 != 0 && i%5 != 0 && i%7 != 0 && i%9 != 0 && i%11 != 0 && i%13 != 0 && i%17 != 0 && i%19 != 0 &&
					i%21 != 0 && i%23 != 0 && i%27 != 0 && i%29 != 0 && i%31 != 0 && i%33 != 0 && i%37 != 0 && i%39 != 0)
					cout << i << ' ';
		}
		
	}

	return 0;
}
Last edited on
You're right, it shouldn't print 11 (and it doesn't).
I guess you posted the wrong code?
my bad, i swore for some reason it was working but just check you're right...
another question though, this stops at 113 for some reason even though i want it to go up to 500... it looks like it stops after the first else if???
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

int main()
{
	for(int i = 3; i < 8000; i++)
	{
		if(i%2 != 0)
		{
			if(i < 9)
				cout << i << ' ';
			else if(i >= 9 && i < 120)
				if(i%3 != 0 && i%5 != 0 && i%7 != 0 && i%9 != 0) 
					cout << i << ' ';
			else if(i > 120 && i < 500)
				if(i%11 != 0 && i%13 != 0 && i%17 != 0 && i%19 != 0)
					cout << i << ' ';
		}
		
	}

	return 0;
}
Last edited on
c++ is not python.
1
2
3
4
5
6
			else if(i >= 9 && i < 120)
				if(i%3 != 0 && i%5 != 0 && i%7 != 0 && i%9 != 0) 
					cout << i << ' ';
			else if(i > 120 && i < 500) //¿with which conditional is paired up?
				if(i%11 != 0 && i%13 != 0 && i%17 != 0 && i%19 != 0)
					cout << i << ' ';
o wow my bad, i was programming in python at the same time and got mixed up, good call
Topic archived. No new replies allowed.