float Series( float fTerms)
{
double dResult = 0;
for(int i = 1; i <= fTerms; i++;) //<--- The last semicolon doesn't need to be there.
dResult = dResult + fTerms;
return dResult;
}
Listen to your compiler. It would have told you there was a syntax error, and exactly what line to find it on.
I went ahead and corrected the syntax error and the code compiled. When I tested the code it is not giving me the sum of the series but actually just squaring the input.
That works also. But making a function for factorial would be a great idea too. There's no performance waste in creating functions. In fact, having more functions is generally good thing. I'm sure somewhere down the line you'll want to find the factorial of something again, then you already have a function written for that.
It's generally good practice to make reusable functions wherever you can. You can't really go wrong with it.
@Thumper
In this case a function call would be a waste. The call to factorial() would need to occur every iteration basically giving it polynomial time complexity. Also, IMO calculating factorial is so trivial code reuse isn't really a big deal (in this specific situation).
My previous code has some typos, this is working for n=5
1 2 3 4 5 6 7
longlong result = 0, factorial = 1;
int n = 5;
for(int i = 1; i <= n; ++i)
{
factorial *= i;
result += factorial;
}
edit:Not sure why I was using long double, but changed to long long.
> The call to factorial() would need to occur every iteration basically giving it polynomial time complexity
Implementation dependent. You could use memorization.
Still, considering how lost is the OP, an aux function would help a lot.
@naraku9333
I'm sorry. For the sake of learning, it's good practice to make reusable functions wherever you can.
Even so, multiple function calls to factorial() (because it's such a simple function) will have such a minuscule affect on process time/resources, especially considering today's technology, that you wouldn't be able to tell a difference.
That said, you're correct. You have given the most efficient solution to the problem.