Recursive program for prime number in C++



We are given an integer as input. The goal is to find whether the input number Num is a prime or non-prime using recursion.

To check if a number is prime or not, start traversing from i=2 to i<=Num/2. If any i is fully divisible by Num then the number is non-prime as prime numbers are only divisible by 1 and the number itself.

Examples

Input − Num = 32

Output − 32 is non-Prime!

Explanation − If we start traversing from i=2 to i<=32/2, then at first it will be fully divisible by 2 which tells it is non-prime.

Input − Num = 43

Output − 43 is a Prime number!

Explanation − If we start traversing from i=2 to i<=43/2, then it will not be divisible by any number between 2 and 21. Which tells it is prime.

Approach used in the below program is as follows

In this approach we are using the recursive function checkPrime(int num1, int index) which takes input number and index which will take values from 2 to num1/2.

For base case-: if num1<2 return 1 as it is non-prime.

If num1==2 return 2 as it is prime.

Else:- if(index<=num1/2) then we reached point upto which no index fully divided num1 so return 1 as it is possible for prime numbers only. Otherwise recurse for next index using result=checkPrime(num1, index+1)

  • Take the input number Num

  • Function checkPrime(int num1,int index) takes inputs and returns 1 if number is prime else returns 0.

  • If num1<2 return 0 as numbers less than 2 are non-prime.

  • If num1 is 2 or 3, return 1 as 2 and 3 are prime numbers.

  • If the num1%index is <= num1/2 then return 1 as upto num1/2 no number fully divided num1 so num1 is prime

  • Recurse for the next index using result=checkPrime(num1, index+1).

  • Return result.

  • Print result obtained inside main.

Example

#include <bits/stdc++.h>
using namespace std;
int checkPrime(int num1, int index){
   if(num1<2){
      return 0;
   }
   if (num1 == 2 || num1==3){
      return 1;
   }
   if (num1 % index == 0){
      return 0;
   }
   if (index <= num1/2){
      return 1;
   }
   int result=checkPrime(num1, index+1);

   return (result);
}
int main(){
   int Num = 31;
   if (checkPrime(Num,2)==1){
      cout <<Num<<" is a Prime number !";
   }
   else{
      cout <<Num<<" is non Prime!";
   }

   return 0;
}

Output

If we run the above code it will generate the following Output

31 is a Prime number!

Advertisements