testing prime numbers

I got a homework, i should make a program to check wether a number is prime or not, made up a code, which works but only halfway. So it recognizes prime numbers but if I input a number that is not prime it get's stuck. Where did I go wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  #include <iostream>
#include <math.h>

using namespace std;

int main()
{
    int n, i, x;
    x = 1;
    i = 2;
    cout <<"n=";
    cin >>n;
    while (i<=sqrt(n))
    {
        if(n%i==0)
        {
            x=0;
        }
        else
        {
            i=3;
        }
    }
    if (x==1)
    {
        cout <<n<<"=prim";
    }
    else
    {
        cout <<n<<"=neprim";
    }
    return 0;
}
Line 21: For every non-prime number, you're resetting the loop counter back to 3.

Suggestion: After line 17, add a break;. Once you know it's not prime, no point in checking further.

Line 13-23: You never increment your loop counter. Did you mean to increment i at line 23?
Thanks, that solved the problem !
Topic archived. No new replies allowed.