program to check prime numbers.

I am a freshman college student. I started to do c++ programming, I was trying to do a program to check whether its prime or not. but it always ssys non prime. I cannot find the problem.
int n,i,j,p;
j= 2*i+1;
while (cin >>n){
if (n%2==0){p=0;}
else { for(i=1;i<=squrt(n);i++){
if (n%j != 0){p=0}
else p=0;

}
}
cout <<p ;
}
somebody please help me. 0 is for npn prime numbers and 1 for prime numbers.
1
2
if (n%j != 0){ p=0 }
else p=0

Read these two lines verbally out loud to yourself.

Also, your code snippet doesn't make sense. j = 2*i + 1 is undefined behavior, because i is not given a value until your for loop. Can you explain what you're trying to accomplish there?

You can only say that a number isn't prime once you determine it isn't divisible by the necessary range of numbers. You can't say that a number is or isn't prime just based on 1 value.

Third, your code does not compile. Post a full program that actually compiles.

Fourth, use code tags. This means putting your code around [code] and [/code] blocks.
Last edited on
First, please use code tags when postig code. See http://www.cplusplus.com/articles/jEywvCM9/

Second, your code is not a full functional program. We can see that it has flaws, but we can't say they are the only ones.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int n, i, j, p; // uninitialized
j= 2*i+1; // unknown value twice is still unknown
while (cin >>n)
{
  if (n%2==0)
  {
    p=0;
  }
  else
  {
    for (i=1; i<=squrt(n);i++)
    {
      if (n%j != 0)
      {
        p=0
      }
      else p=0;
    }
  }
  cout <<p ;
}

Lines 13-17 have
IF cond THEN p=0 ELSE p=0

No matter what the cond is, you always do p=0. Lets reduce that code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int n, i, j, p; // uninitialized
j= 2*i+1; // unknown value twice is still unknown
while (cin >>n)
{
  if (n%2==0)
  {
    p=0;
  }
  else
  {
    for (i=1; i<=squrt(n);i++)
    {
      p=0;
    }
  }
  cout <<p ;
}

Now lines 11-14 set p=0, unless squrt(n) < 1.
Furthermore, the j is not used anywhere.
Another clarification:
1
2
3
4
5
6
7
8
9
10
11
12
13
int n, i, p; // uninitialized
while (cin >>n)
{
  if ( n%2==0 )
  {
    p=0;
  }
  else if ( 1 <= squrt(n) )
  {
    p=0;
  }
  cout <<p ;
}

That is what your code essentially does.
We see that if n is even or 1<=squrt(n), then p==0.
For the remaining cases we do not know, because p has no known value before the while-loop.


PS. Why the UNIX/Linux section and not the Beginners section?
Topic archived. No new replies allowed.