Skip to content

Commit d99e1ca

Browse files
authored
Merge pull request #3 from cinfinit/master
Primality Test C++
2 parents 5e5edad + ad2591b commit d99e1ca

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

PrimalityTest/c++/primality.cpp

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#include <iostream>
2+
using namespace std;
3+
// following are the very basic approaches
4+
5+
//method 1
6+
/*
7+
bool isPrime(int n)
8+
{
9+
// Corner case
10+
if (n <= 1) return false;
11+
12+
// Check from 2 to n-1
13+
for (int i=2; i<n; i++)
14+
if (n%i == 0)
15+
return false;
16+
17+
return true;
18+
}
19+
*/
20+
//Time complexity of this solution is O(n)
21+
22+
23+
24+
//method 2
25+
bool isPrime(int n)
26+
{
27+
// Corner cases
28+
if (n <= 1) return false;
29+
if (n <= 3) return true;
30+
31+
// This is checked so that we can skip
32+
// middle five numbers in below loop
33+
if (n%2 == 0 || n%3 == 0) return false;
34+
35+
for (int i=5; i*i<=n; i=i+6)
36+
if (n%i == 0 || n%(i+2) == 0)
37+
return false;
38+
39+
return true;
40+
}
41+
//Time complexity of this solution is O(underroot n)
42+
43+
int main(void){
44+
// to check whether n is prime or not
45+
int n ;
46+
//taking input from the user
47+
cin>>n;
48+
49+
isPrime(n) ? cout<<"The number is prime ":cout<<"Number is not prime ";
50+
51+
return 0;
52+
53+
}

0 commit comments

Comments
 (0)