From bd97f4e0b49527e3278b7c3ce7e6300d754d9efc Mon Sep 17 00:00:00 2001 From: Puneet Goel Date: Tue, 12 Oct 2021 09:30:10 -0700 Subject: [PATCH] chore(CPlusPlus): add Recursive Prime Checker (#548) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Co-authored-by: Ujjwal <75884061+UG-SEP@users.noreply.github.com> --- algorithms/CPlusPlus/README.md | 2 +- .../CPlusPlus/Recursion/recursive-prime.cpp | 72 +++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 algorithms/CPlusPlus/Recursion/recursive-prime.cpp diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index abda067c..56b05835 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -137,4 +137,4 @@ - [Sum of all elements of an array](Recursion/Sum-of-all-elements-in-an-array.cpp) - [Decimal number to Binary conversion](Recursion/decimal-to-binary-conversion.cpp) - [Sum of digits of a decimal integer](Recursion/sum-of-digits-of-an-integer.cpp) - +- [Prime Check](Recursion/recursive-prime.cpp) diff --git a/algorithms/CPlusPlus/Recursion/recursive-prime.cpp b/algorithms/CPlusPlus/Recursion/recursive-prime.cpp new file mode 100644 index 00000000..695a275b --- /dev/null +++ b/algorithms/CPlusPlus/Recursion/recursive-prime.cpp @@ -0,0 +1,72 @@ +/* +Problem: Check if a given number is prime or not, using Recursion +*/ + +#include +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" <