-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recursive-prime.cpp
72 lines (57 loc) · 1.09 KB
/
recursive-prime.cpp
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
Problem: Check if a given number is prime or not, using Recursion
*/
#include <bits/stdc++.h>
using namespace std;
// primeCheck is function that check whether the given number is prime or not and,
// return true if prime else
// return false
bool primeCheck(int n, int i)
{
// Base cases
if(n <= 2){
// 2 is a prime
if(n == 2){
return true;
}
// 0 and 1 are not prime
return false;
}
// if i divides n then n is not prime
if(n % i == 0){
return false;
}
if(i * i > n){
return true;
}
// Check for next possible divisor
return primeCheck(n, i + 1);
}
// Main
int main()
{
cout << "Enter the number to check prime : " << endl;
int n;
cin >> n;
//check and output
if (primeCheck(n, 2))
cout << "YES" <<endl;
else
cout << "NO" <<endl;
return 0;
}
/*
Time Complexity : O(sqrt(n))
Input
Enter the number to check prime : 5
Output
YES
Input
Enter the number to check prime : 10
Output
NO
Input
Enter the number to check prime : 33
Output
NO
*/