Skip to content

Commit 0265571

Browse files
authored
Adding algorithm to check if number is prime or not. (TheAlgorithms#834)
* Optimized algorithm to check if number is prime or not. * logic to check if given number is prime or not. * logic to check if given number is prime or not. * logic to check if given number is prime or not. * logic to check if given number is prime or not. * Included appropriate comments as per standards. * variable name renamed to num * added @file and @brief in comment. Also added template and variable name changed from is_prime to result * added @file and @brief in comment. Also added template and variable name changed from is_prime to result * added template parameter T type in loop
1 parent 2829734 commit 0265571

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

math/check_prime.cpp

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/**
2+
* Copyright 2020 @author omkarlanghe
3+
*
4+
* @file
5+
* A simple program to check if the given number if prime or not.
6+
*
7+
* @brief
8+
* Reduced all possibilities of a number which cannot be prime.
9+
* Eg: No even number, except 2 can be a prime number, hence we will increment our loop with i+2 jumping on all odd numbers only.
10+
* If number is <= 1 or if it is even except 2, break the loop and return false telling number is not prime.
11+
*/
12+
#include <iostream>
13+
#include <cassert>
14+
/**
15+
* Function to check if the given number is prime or not.
16+
* @param num number to be checked.
17+
* @return if number is prime, it returns @ true, else it returns @ false.
18+
*/
19+
template<typename T>
20+
bool is_prime(T num) {
21+
bool result = true;
22+
if (num <= 1) {
23+
return 0;
24+
} else if (num == 2) {
25+
return 1;
26+
} else if ((num & 1) == 0) {
27+
return 0;
28+
}
29+
if (num >= 3) {
30+
for (T i = 3 ; (i*i) < (num) ; i = (i + 2)) {
31+
if ((num % i) == 0) {
32+
result = false;
33+
break;
34+
}
35+
}
36+
}
37+
return (result);
38+
}
39+
40+
/**
41+
* Main function
42+
*/
43+
int main() {
44+
int num;
45+
std::cout << "Enter the number to check if it is prime or not" <<
46+
std::endl;
47+
std::cin >> num;
48+
bool result = is_prime(num);
49+
if (result) {
50+
std::cout << num << " is a prime number" <<
51+
std::endl;
52+
} else {
53+
std::cout << num << " is not a prime number" <<
54+
std::endl;
55+
}
56+
assert(is_prime(50) == false);
57+
assert(is_prime(115249) == true);
58+
}

0 commit comments

Comments
 (0)