I had to write a program that prompts the user to input a positive integer.It should then output a message indicating whether the number is prime number. The problem with my code it is that give the two answer when not it prime. The code is:
#include <iostream>
#include <cmath>
usingnamespace std;
int main ()
{
int num;
int i;
int root;
cout << "Please enter a number: ";
cin >> num;
cout << endl;
root = pow(num, 0.5);
if (num != 0)
{
if (num < 0)
cout << "Please enter a positive integer."
<< endl;
elsefor (i=2; i<= root; i++)
if (num % i == 0)
cout << "It is not prime number." << endl;
}
cout << "IT A PRIME NUMBER" << endl;
return 0;
}
You output that it is a prime number no matter what...
I would add another variable (something like 'bool is_it_prime = true'). Then, when your loop finds that it is _not_ prime, set 'is_it_prime' to false and break the loop.
Then, down at the bottom, use an 'if' statement to check whether is_it_prime is true or false and print an appropriate message.
BTW. You should also be careful about 0 and 1. Neither are prime.
#include <iostream>
#include <cmath>
usingnamespace std;
int main ()
{
int num;
int i;
int root;
bool prime;
cout << "Please enter a positive number: ";
cin >> num;
cout << endl;
root = pow(num, 0.5);
for (i=2; i<= root; i++)
{
if (num % i == 0)
{
cout << "It is not prime number." << endl;
prime = false;
}
else
{
cout << "IT IS PRIME NUMBER." << endl;
prime = true;
}
}
return 0;
}
Take a look at your code and think about where the output statements are. Every time through the loop the number is tested against a potential factor and something is printed either way.
You should only declare (print) whether the number is prime or not _after_ checking all possible factors.
Also, you should pay attention to the wording I used in the last post about your 'prime' variable: you should start off assuming it is prime and then disprove it.