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

Examples

Input − Num = 32

Output − 32 is non-Prime!

Explanation − If we start traversing from i=2 to i

Input − Num = 43

Output − 43 is a Prime number!

Explanation − If we start traversing from i=2 to i

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

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

Else:- if(index

  • 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

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

  • If the num1%index is

  • 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!
Updated on: 2021-11-02T08:26:06+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements