16.6k views
4 votes
Write C++ a function name int min_divisor(int n) that returns the minimum divisor of a number recursively without using any built in C++ classes such as Math.

User Goodov
by
7.9k points

1 Answer

6 votes

Answer:

The program to this question can be given as:

Program:

#include<iostream> //include header file.

using namespace std;

int min_divisor(int n) //define function

{

if(n<=0) //if statement (base case)

{

return -1; //return value.

}

else

{

cout<<"Recursive Function call: "<<n<<endl; //print value

for(int i=2;i<n/2;i++) //loop

{

if(n/i==0) //if statement

{

return n/i; //return value.

}

}

}

}

int main() //main function

{

int n; //variable decalration

cout<<"Enter a number:";

cin>>n;

int res=min_divisor(n); //calling function

cout<<"min divisor is: "<<res<<endl; //print value

}

Output:

Enter a number: 5

Recursive Function call: 5

min divisor is: 2

Explanation:

In the above program firstly we include the header file that is iostream. It stands for standard input output stream.Then we declare a function that name is already given in question that is min_divisor(int n). In this function there is a one parameter. In the function we use if-else statement in if block n less then equal to 0 it will return value that is -1. In else block It will print the value first then we use the loop. It starts from the 2 and end from n/2. In this loop we divide the value of n and check that if the value is equal to 0 so it will return n/i. Then we declare the main function in the main function we declare variable in this variable we take user input and pass into the function by calling it and hold the return value of the function into variable res variable and print it.

User Thedude
by
7.5k points