Write a recursive function that prints the following series:
1/1!+1/2!+1/3!+1/4!+⋯+1/𝑛!
Write only the function. You cannot use loops. Use the empty box below to write your answer. Calculating the sum of the series is not necessary, just print the series.
Following is an example of how the function can be called and its output.
dont know how to do this code. plz help me out here
#include <iostream>
usingnamespace std;
float invRecStatement(int);
void printFactorial(int);
float sum(int);
int main()
{
//snazzy intro
cout << "Inverse Factorial Finder!\n=========================\n\n";
//enter a value x to start factorial
int x;
cout << "enter a number to begin the factorial: ";
cin >> x;
printFactorial(x);
//might as well get the sum right?
cout << "the sum of the inverse factorial is: " << sum(x) << endl;
}
float invRecStatement(int fac)
{
//break statement
//
//you need to include this in your recursive statement to avoid
//infinite loop.
if(fac == 1)
{
return 1;
}
int factorial = fac * invRecStatement(fac - 1);
//returns the passed value multiplied by the function of the passed value minus one
return factorial;
}
void printFactorial(int num)
{
//this prints the algorithm however many times the number entered in the program
//
//the incremental operator and conditional were shifted to one to avoid dividing by zero at start.
for(int inc = 1; inc < num + 1; inc++)
{
cout << "1/" << invRecStatement(inc) << " + ";
}
cout << endl;
}
float sum(int num)
{
float accumulatedValue = 0;
for(int inc = 1; inc < num + 1; inc++)
{
accumulatedValue += 1/invRecStatement(inc);
}
return accumulatedValue;
i didn't catch the no using loops bit but i assume that he or she is only talking about the actual math bit, if not you could always replace the loops with a recursive void that counts down an int. what I did was break up the algorithm into two parts, the numerator one and the factorial part, since the "1/" part always occurs and you just need the factorial you can put it in a recursive function or loop that prints out that part and then feed a value into a parameter calculating the actual factorial.
on the first loop i shifted everything up one because the program divided the first part by zero, i feel that doing that was just an easy out, would anyone know of a better way?