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.
#include <iostream>
usingnamespace 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.
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.
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.