I'm trying to make a code that outputs prime numbers. I wrote an if statement that says if the number is not divisible by any numbers less than its square root, then output that number. However, it outputs the number every time it's true, rather than checking for all values of i before continuing. Is there a way that I can make it so it checks that the remainder of x/i is not 0 for ALL values of i before outputting x???
int num;
int x;
float sq;
int main()
{
cin >> num;
for (x=num; x>=1; x--)
{
sq = sqrt(x);
for (int i=1; i<sq; i++)
{
if ( x % i != 0)
{
cout << x;
cout << endl;
}
}
}
return 0;
}
int num;
int x;
float sq;
int main()
{
cin >> num;
for (x=num; x>=1; x--)
{
sq = sqrt(x);
bool prime = true;
for (int i=2; i<sq; i++)
{
if ( x % i == 0)
{
prime = false;
break;
}
}
if (prime)
cout << x;
}
return 0;
}
Here, you set a flag to true by default. If any of the numbers in range [2, sqrt(x)] is a divisor or x, the flag will be set to false and we break out of the loop. If none of those numbers is a divisor, we reach the end of the loop without ever setting the flag to false.
Of course, if you do want to check all cases before printing something, then check all cases before printing.
You have:
1 2 3 4 5 6 7 8 9 10 11
{
sq = sqrt(x);
for (int i=1; i<sq; i++)
{
if ( x % i != 0)
{
cout << x;
cout << endl;
}
}
}
Lets move the print after the testing:
1 2 3 4 5 6 7 8 9 10 11 12
{
sq = sqrt(x);
for (int i=1; i<sq; i++)
{
if ( x % i != 0)
{
}
}
// now we have tested every case
cout << x << '\n';
}
Oh, we should not print every x, just those that are prime. We have to transfer information from the loop to the print. With a variable:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
{
bool isPrime = true; // every number is prime, unless proven divisible
sq = sqrt(x);
for (int i=1; i<sq; i++)
{
if ( x % i != 0)
{
}
}
// now we have tested every case
if ( isPrime )
{
cout << x << '\n';
}
}
The only thing that remains is to change the isPrime in the loop, if the x is not a prime.