output problem with if number is prime or not
Hi
I was trying to write a code to know if the entered number is prime or not. It works fine other that it gives several outputs saying numbers is prime or not prime. How do I fix it so that it shows only once if the number is prime or not? Please help me. Thanks
Code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int n, i;
bool prime, notprime;
cout << "Enter the number: ";
cin >> n;
for (i=2; i<=(n/2);i++)
{
if (n%i != 0)
cout << "prime" << endl;
else
cout << "notprime" << endl;
}
system("pause");
}
Output:
Code:
Enter the number: 13
prime
prime
prime
prime
prime
Press any key to continue . . .
Re: output problem with if number is prime or not
Try:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int n, i;
bool prime=true;
cout << "Enter the number: ";
cin >> n;
for (i=2; i<=(n/2);i++)
{
if !(n%i != 0)
prime = false;
}
if (prime)
cout << "prime" << endl;
else
cout << "notprime" << endl;
system("pause");
}
Re: output problem with if number is prime or not
Quote:
Originally Posted by
heights
I was trying to write a code to know if the entered number is prime or not. It works fine other that it gives several outputs saying numbers is prime or not prime. How do I fix it so that it shows only once if the number is prime or not? Please help me. Thanks
The logic in your program is flawed. If a number is dividable by any number other than 1 or itself, it is not a prime. If it is only dividable by 1 and itself, it is a prime.
Re: output problem with if number is prime or not
Quote:
Originally Posted by
Eaglei022
Try:
Merely providing the solution doesn't help people to learn from their mistakes.
And you should use code tags when posting code.
Re: output problem with if number is prime or not
Quote:
Originally Posted by
D_Drmmr
Merely providing the solution doesn't help people to learn from their mistakes.
And you should use code tags when posting code.
Yeah, just giving a solution doesn't help. If that solution is explained, that'd be a lot better. On the other hand, you just have to hope they'll read it. :P So, here goes.
The for loop is what checks the divisibility. It starts at 2, since 1 will divide anything. The expression in the if block should be "n % i == 0", as that is more readable. If the remainder is 0, n cannot be prime, so it sets the 'prime' flag to false. And it would be better to have it break out of the for loop after setting prime to false, since no more tests are needed. See if you can modify this to just check 2 and odd numbers.
Re: output problem with if number is prime or not
And, you can stop your loop sooner then you are currently...
Viggy
Re: output problem with if number is prime or not
Thanks a lot, everyone. I will ask some follow-on questions tomorrow.
Best regards
H