Prime number code

What's wrong with this code? I learned it at school. It doesn't work for some numbers, including 7,11 and 121. But for the rest it does.

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
  #include<iostream>
using namespace std;
int main ()
{
    int x,ok,i;
    cin>>x;
    if(x%2==0)
        if (x==2)
            ok=1;//este prim
        else
            ok=0;//nu este prim
    else
        {
        ok=1;
        i=3;
        while(i<=x/2&&ok==1)
            if(x%i==0)
                ok=0;
            i=i+2;
        }
    if(ok==1)
        cout<<"nr este prim";
    if(ok==0)
        cout<<"nr nu este prim";
    return 0;
}
Always use braces with if, else, while etc. Here is your code, indented to match the actual block structure. I've highlighted the line that matters.
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
#include<iostream>
using namespace std;
int
main()
{
    int x, ok, i;
    cin >> x;
    if (x % 2 == 0)
	if (x == 2)
	    ok = 1;				 //este prim
	else
	    ok = 0;				 //nu este prim
    else {
	ok = 1;
	i = 3;
	while (i <= x / 2 && ok == 1)
	    if (x % i == 0)
		ok = 0;
	i = i + 2;
    }
    if (ok == 1)
	cout << "nr este prim";
    if (ok == 0)
	cout << "nr nu este prim";
    return 0;
}

Topic archived. No new replies allowed.