# Thread: checking if number is prime

1. ## checking if number is prime

Hi

Do you find the below given code correct? Any suggestions?

One major problem is that the prime's state true or false is shown with "1" or "0" respectively. How do I get output such as "the number is prime" and "the number is not prime"? Please help me. Thanks a lot.

Code:
```#include <iostream>
#include <cstdlib>

using namespace std;

int main()

{
int n, i;
bool prime;

cout << "Enter the number: ";
cin >> n;

for (i=2; i<=(n/2);i++)

{
if (n%i != 0)
prime = true;

else
prime = false;

{
if (prime = false)
break;
}
}

cout << prime << endl;

system("pause");
}```

2. Have you increased the warning levels for your compiler yet?
Code:
```\$ g++ -Wall foo.cpp
foo.cpp: In function ‘int main()’:
foo.cpp:26: warning: suggest parentheses around assignment used as truth value```
Referring to this line
if (prime = false)

Also, you only need to go up to sqrt(n), not n/2

> for (i=2; i<=(n/2);i++)
A very easy win is to start at 3, and then increase by 2 each time (thus missing all the even numbers)

> How do I get output such as "the number is prime" and "the number is not prime"?
Use an if statement - you have several examples already.
if it's true, print something, or print something else.

3. Originally Posted by jackson6612
Hi

Do you find the below given code correct? Any suggestions?

One major problem is that the prime's state true or false is shown with "1" or "0" respectively. How do I get output such as "the number is prime" and "the number is not prime"? Please help me. Thanks a lot.

Code:
```#include <iostream>
#include <cstdlib>

using namespace std;

int main()

{
int n, i;
bool prime;

cout << "Enter the number: ";
cin >> n;

for (i=2; i<=(n/2);i++)

{
if (n%i != 0)
prime = true;

else
prime = false;

{
if (prime = false)
break;
}
}

cout << prime << endl;

system("pause");
}```
You shouldn't use if statement with single '=' because its makes prime false every time then break. It should be if (prime == false).

And if you want to print if its prime or not use : if(prime) cout << "It is prime" << endl; else cout << "It is not prime" << endl;
-

4. Thanks a lot, Salem, kargo.

Best regards
Jackson

5. Why set it to false and then immediately test if it is false and do the break? Why not just set it to false and break at the same time in the else case?