prime number testing

Testing prime number. could anyone pls help me to look for the error here, when i input 13, a prime number, it is not working properly. thanks a lot.


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

int n;
cout<<"Please enter a number: ";
cin>>n;

if(n<=1)
exit(1);

for(int i=2; i<=n; i++){
if(n%i==0)
cout<<"Not a prime."<<endl;
return 0;

}
cout<<"It is a prime."<<endl;

return 0;
}
Proper indentation helps to make it clear what is happening:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
using namespace std;

int main() 
{

    int n;
    cout<<"Please enter a number: ";
    cin>>n;

    if (n<=1)
        exit(1);

    for (int i=2; i<=n; i++)
    {
        if (n%i==0)
            cout<<"Not a prime."<<endl;

        return 0;
    }
    cout<<"It is a prime."<<endl;

    return 0;
} 


There are a couple of errors. Line 14 should test <n instead of <=n
The "if" at line 16 requires braces around the lines which depend on it. In the original version, the return statement at line 19 is always executed, regardless of the "if" statement.

1
2
3
4
5
6
7
8
9
    for (int i=2; i<n; i++)
    {
        if (n%i==0) 
        {
            cout<<"Not a prime."<<endl;
            return 0;
        }
    }
    cout<<"It is a prime."<<endl;
Last edited on
i got it thanks for your time, =]
Topic archived. No new replies allowed.