Check for Prime number

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>

#include <cmath>

using namespace std;

int main()
{
	int n;

	cout<<"Enter a number: ";

	cin>>n;

	bool is_prime = true;

	if (n < 2)
	{
		is_prime = false;
	}

	else if (n == 2)
	{
		is_prime = true;
	}

	else if (n % 2 == 0)
	{
		is_prime = false;
	}

	else
	{
		for (int div = 3; div <= sqrt(n); div++)
		{
			if (n % div == 0)
			{
				is_prime = false;

				break;
			}
		}
	}

	if (is_prime == true)
	{
		cout<<"The number "<<n<<" is a prime number."<<endl;
	}

	else
	{
		cout<<"The number is not a prime number"<<endl;
	}

	return 0;
}



Is my code alright? Please help.
try testing before posting ;)

I just compiled it (compiled fine) and ran it..

Judging by the outputs it's alright :)

Cheers!
I think that you may have trouble with div <= sqrt(n), because of round-off errors.
Besides that it is correct, but could be faster.
Last edited on
Topic archived. No new replies allowed.