C++ Program to Display Factors of a Number using Recursion














































C++ Program to Display Factors of a Number using Recursion



The factor of a Number Explanation :
The factor of a number is a number which can divide that number and give 0 as remainder. Thus, it is clear that we have to use n%i condition and this should be equal to zero. So there's a function is Factor(int i, int n). This function is responsible to check as well as to print the factor.
The flow of the Program:
 In this code, it's clear that while running, it starts from the main function as the main function is a static function and it is the first function that gets executed at first. User is asked to enter the value of the number, whose factors are intended to find. When the control goes to is Factor function :
Step 1: It checks whether the first value of i that's 2, divides the number 'n' or not. If it does, it prints.
Step 2:  It checks whether we have reached the end limit or not. If yes, then it exits the code after printing the number itself as every number is the factor of itself.
Step 3: If the second condition fails, it let the process to continue and follow the recursive method to call the function again.

Drawbacks of this code:

Recursion is avoided generally because it makes the code less readable. If one has low resources as stack space, one so should avoid using it then.

Merits of the code:

Easy to debug and small logic has written using recursion.


CODE

#include<iostream>
using namespace std;

void isFactor(int i,int n)
{
        if(n%i==0)
{
cout<<i<<",";
}
if(i+1==n)
{
                                 cout<<n;
exit;
}
else
{
 isFactor(i+1,n);
}
        }
int main() 
        {
int n;
cout<<"Enter number to get it's factor: ";
cin>>n;
isFactor(2,n);
        }


More Articles of Shraddha Gulati:

Name Views Likes
C++ Program to Display Factors of a Number using Recursion 248 22

Comments