mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-04-05 03:29:46 +08:00
@@ -107,6 +107,7 @@
|
||||
|
||||
## Math
|
||||
* [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp)
|
||||
* [Check Prime](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/check_prime.cpp)
|
||||
* [Double Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/double_factorial.cpp)
|
||||
* [Eulers Totient Function](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/eulers_totient_function.cpp)
|
||||
* [Extended Euclid Algorithm](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/extended_euclid_algorithm.cpp)
|
||||
|
||||
58
math/check_prime.cpp
Normal file
58
math/check_prime.cpp
Normal file
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Copyright 2020 @author omkarlanghe
|
||||
*
|
||||
* @file
|
||||
* A simple program to check if the given number if prime or not.
|
||||
*
|
||||
* @brief
|
||||
* Reduced all possibilities of a number which cannot be prime.
|
||||
* 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.
|
||||
* If number is <= 1 or if it is even except 2, break the loop and return false telling number is not prime.
|
||||
*/
|
||||
#include <iostream>
|
||||
#include <cassert>
|
||||
/**
|
||||
* Function to check if the given number is prime or not.
|
||||
* @param num number to be checked.
|
||||
* @return if number is prime, it returns @ true, else it returns @ false.
|
||||
*/
|
||||
template<typename T>
|
||||
bool is_prime(T num) {
|
||||
bool result = true;
|
||||
if (num <= 1) {
|
||||
return 0;
|
||||
} else if (num == 2) {
|
||||
return 1;
|
||||
} else if ((num & 1) == 0) {
|
||||
return 0;
|
||||
}
|
||||
if (num >= 3) {
|
||||
for (T i = 3 ; (i*i) < (num) ; i = (i + 2)) {
|
||||
if ((num % i) == 0) {
|
||||
result = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return (result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Main function
|
||||
*/
|
||||
int main() {
|
||||
int num;
|
||||
std::cout << "Enter the number to check if it is prime or not" <<
|
||||
std::endl;
|
||||
std::cin >> num;
|
||||
bool result = is_prime(num);
|
||||
if (result) {
|
||||
std::cout << num << " is a prime number" <<
|
||||
std::endl;
|
||||
} else {
|
||||
std::cout << num << " is not a prime number" <<
|
||||
std::endl;
|
||||
}
|
||||
assert(is_prime(50) == false);
|
||||
assert(is_prime(115249) == true);
|
||||
}
|
||||
Reference in New Issue
Block a user