The document discusses converting a recursive function that finds all divisors of a number into an iterative function. It provides the code for the original recursive function that takes a number as a parameter and recursively calls itself to find all divisors. The solution section then explains that the function needs to be manipulated to remove recursion and instead use iteration, and provides the code for an iterative version that uses a for loop to find all divisors and print them.
How to turn this recursive function into an iterative function- #inclu.docx
1. How to turn this recursive function into an iterative function:
#include <iostream>
#include <cmath>
using namespace std;
void get_divisors(int n);
int main() {
int n = 0;
cout << "Enter a number and press ENTER: ";
cin >> n;
get_divisors(n);
cout << endl;
return 0;
}
void get_divisors(int n) {
int i;
double sqrt_of_n = sqrt(n);
for (i = 2; i <= sqrt_of_n; i++)
if (n % i == 0)
{
cout<<i<<",";
get_divisors(n / i);
return;
}
cout << n;
}
Solution
Above function is a recursive functive which means a function which calls it self.
2. function calling it self should manipulated for iterative function
iterative function
#include <iostream>//header file for input ut function
using namespace std;//it tells the compiler to link std name space
void get_divisors(int n);//function declaration
int main() {
int n = 0;
cout << "Enter a number and press ENTER: ";
cin >> n;//keyboard inputting
get_divisors(n);//calling function
cout << endl;
return 0;
}
void get_divisors(int n) {//function definition
int i;
for (i = 2; i <= n; i++){
if (n % i == 0)
{
cout<<i<<",";
}
}
return;
cout << n;
}
output
Enter a number and press ENTER: 60 2,3,4,5,6,10,12,15,20,30,60,