Output all prime numbers between 1 and 100

Hi there, I just got and assignment asking me to write a program that outputs all the prime numbers between 1 and 100. The only main requirement is that I have to use nested while loops.

Here's my code so far,

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
#include <iostream>
using namespace std;
 
int main()
{
    int num, i, f;
    num = 1;
    f = 0;
    i = 2;

    while (num <= 100){
		i=2;

	while(i <= num/2)
	{
		if(num%i == 0)
		{
			f=1;
			break;
		}

		i++;
	}

	if(f == 0)
		cout<<num<<endl;

	num = num + 1;

}
 
return 0;

}


I know the issue has to do with my first while loop as my output is,

1
2
3


I've been having trouble grasping the concept of nested while loops so if anyone would be willing to help me understand what I did wrong I'd be extremely grateful.

Thanks!
Last edited on
Q. What does the inner loop do?
A. It sets f=1, if num is not prime.

Q. What is the value of f before that loop?
Before the inner loop, the value of f is 0.
... but only the first time through the outer loop since you don't reinitialize it to 0.
Is it? Insert on line 13:
cout << "Checking " << num << " f=" << f << '\n';
and test.
@keskiverto

Yes I see now. I corrected my mistake.

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
#include <iostream>
using namespace std;
 
int main()
{
    int num, i, f;
    num = 1;
    f = 0;
    i = 2;

    while (num <= 100){
		i=2;
		f=0;

	while(i <= num/2)
	{
		if(num%i == 0)
		{
			f=1;
			break;
		}

		i++;
	}

	if(f == 0)
		cout<<num<<endl;

	num = num + 1;

}
 
return 0;

}
Last edited on
Thanks so much for your help!
Last edited on
You should start num at 2 (1 is neither prime nor composite).

And you only need to check up to the square root of the number, which you can do by changing your inner while loop to:

 
        while( i * i <= num )

This makes a big difference when determining if a large(ish) number is prime.
For really big numbers it's not feasible to test for primality in this way at all.
Last edited on
Ah okay. I forgot that 1 isn't actually a prime number. As for changing the while loop, I see that your while loop statement is a lot more efficient. As I'm only finding the prime numbers up to 100, my code works fine, however since yours is more efficient ill be changing it.

Thanks so much for your help, I really appreciate it.
Topic archived. No new replies allowed.