Norway


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

Examples:

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";
    else
        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 contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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 contribute@geeksforgeeks.org to report any issue with the above content.




Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here