Given a n, check whether it’s prime number or not using recursion.


Input : n = 11
Output : Yes

Input : n = 15
Output : No

The idea is based on school method to check for prime numbers.

// CPP  to find whether a Number   
// is  or Not using Recursion
#include <bits/stdc++.h>
using namespace std;

// Returns true if n is , else
// return false.
// i is current divisor to check. 
bool isPrime(int n, int i = 2)
    // Base cases
    if (n <= 2)
        return (n == 2) ? true : false;
    if (n % i == 0)
        return false;
    if (i * i > n)
        return true;

    // Check for next divisor
    return isPrime(n, i + 1);

// Driver Program
int main()
    int n = 15;
    if (isPrime(n))
        cout << "Yes";
        cout << "No";

    return 0;

- kkqk1dmz74gp7evlqflj - Recursive program for prime number

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Please write to us at to report any issue with the above content.

Source link


Please enter your comment!
Please enter your name here