If you look at
the topic stickied on the top of this forums, you'll find a nice explanation of the differences between iterative and recursive functions and making the algorithm yourself shouldn't be such a problem if you give it a bit of effort.
The Alchemist: The int datatype is completely inappropriate for this. If you tried any even a bit larger number you would find that it's going to start giving you bad results, because it will overflow. Also the code is kinda messy and probably not the best solution.
----------------------------------------
Here's probably the best way to do this and approach the problem:
What do you need to do is to determine how to calculate each element of the series and how to nest this calculation in itself.
You also need some stop condition, which will always return at the end. Let's use the same one as if we were to calculate just the factorial.
The problem with that approach is that we need to return two values from a function - the factorial (so it can be used for further calculation) and the sum of the elements before. So that's what we will do! You can return more values from a function using an argument, if you make it into a pointer. Then the function can place any value into it that you can read later.
Here's my implementation:
Code:
#include <iostream>
using namespace std;
double SumFactorials(int n, double *fact = 0)
{
// the stop condition
if(n <= 1)
{
// factorial of 1 or 0 is always 1
if(fact)
*fact = 1;
return 1; // this is the sum
}
// caltulate the subFactorial (n-1)! first
double subFact;
double sum = SumFactorials(n-1, &subFact);
// now we've got both sum of (n-1) and the factorial, so let's calculate current element
if(fact)
*fact = n*subFact;
return n*subFact + sum;
}
void main()
{
for(int n = 1; n < 20; n++)
cout << n << " -> " << SumFactorials(n) << endl;
cin.get();
}
Notice how I also used default parameter for a function to make the pointer null by default - the top function doesn't need to return the factorial, only the sum, so you can call it simply by SumFactorials(n), where n is the same n as in your equation. No other arguments are needed, it's nice, simple and clean.
Let me know if you don't understand any part of it or need any further help.