Determine prime number

Can someone tell me whats wrong with my code?? No matter what number i put in, the number is not prime, thanks.

The following is my code:

#include<iostream>
using namespace std;
int main(){

int a,b, is_prime=true;
cout<<"Enter a number:";
cin>>a;

b=2;
while (b<a){
if (a%b != 0)
is_prime=true;
b++;
}

if (is_prime=true)
cout<<"Number is not prime";

else
cout<<"Number is prime";
system("PAUSE");

return 0;
}
First off all your loop for determining whether the number is prime or not is not correct. You always will get that the number is prine because the last iteratiion of the loop tries to divide a by a-1. And as result is_prime will be set to true.
Also instead of using the comparision operator (==) you use the assignment operator (=) in the following statement

if (is_prime=true)
Last edited on
or just
1
2
if (is_prime)
  cout<<"Number is not prime"; // ¿? 


It seems that you don't understand what "for all" or "exists" means
Thanks for the advice. The logic behind my code is:
1) Input number eg: 10
2) Divide number by every number till x-1 eg: Divide 10 by 2, Divide 10 by 3.......Divide 10 by 9 .
3)If there are remainders every time you divide, Number is Prime

else

Number is not prime.

Can someone show me how the coding should be like?? Big Thank you in advance
Last edited on
For example you may do the following way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int x;
bool is_prime = true;

cout << "Enter a number:";
cin >> x;

for ( int i = 2; i <= x / 2; i++ )
{
   if ( x % i  == 0 )
   {
      is_prime = false;
      break;
   }
}
Last edited on
Topic archived. No new replies allowed.