Confused about my prime number assignment

Hello everyone.

I am currently doing an intro C++ assignment and ran into some confusion. The code is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

        int n = 0;
	int i = 2;
	bool primenumber = true;

	cout << "Enter a number and press ENTER: " << endl;
	cin >> n;

	while (i <= sqrt(n)) { if (n%i == 0) {primenumber = false; } ++i; }

	if (primenumber) { cout << "Number is prime." << endl; }
	else { cout << "Number is not prime." << endl; }

	
	

    return 0;


I understood all of it except one thing: "++i"

Why do we add one to "i"? I noticed when I took it out, the program would not print "Number is not prime." for non prime numbers. I thought about it for a while but still couldn't grasp its significance.

If someone could point me in the right direction it would be really helpful.

Thank you.
Last edited on
n being the number that is checked if it's prime or not.

The reason you increase i is because you divide n by i and check the remainder. By doing this you check if n has any factors or is divisible (if it is it's not prime and it has a remainder of 0). If all the divisions (i increases) come out as not 0 then it is prime.
The i is inside the while loop. At your above code formatting this could quite be overlooked.
1
2
3
4
5
6
while  (i <= sqrt(n) ) {
    if (n%i == 0) { 
        primenumber = false; 
    }
    ++i; 
}
++i == i = i + 1
Example:

Let's say that you entered in 10 in your program. Then the program would do this:
remainder of 10 ÷ 2, remainder 10 ÷ 3, remainder of 10 ÷ 4, etc.

If any of those remainders are 0 then it is not a prime number. If none of the remainders are 0 then it is a prime number.

Hope that helped.
Last edited on
Topic archived. No new replies allowed.