I'm not going to post the whole code since it's pretty long but I'll give a few snips of the important stuff.
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
#include <iomanip>
#include <math.h>
usingnamespace std;
int main()
{
string ch;
int num, num1, num2, num3, num4, dividend, divisor, N, factorial;
float num6, num7, num8, num9, max, M;
...lots of code in between....
1 2 3 4 5 6 7
else
{
cout << "\nEnter the factorial number: ";
cin >> num;
factorial = (num * num) + (num * ((num + 1) - 1));
cout << "The factorial of " << num << " is " << factorial;
}
Now I'm having the issue of getting this down. For example, I want the exponential of 5 when I put it in to be 125. Any suggestions? I tried doing for statements and if statements but I could never figure this out.
Just a side question, who like recursion a lot ? I notice some programmers possibly used other highly recursive programming language before coming to C++ will use their habits in C++. I maintain ppl code and some developer has some "fanatical" obsession to change snippet of codes into recursive style when sometimes a simple for loop will suffice :O
int factorial(int n) { //please pass in n >= 0
return (n==0) ? 1 : n * factorial(n-1);
}
I wonder if the iteration version would have more statements than a recursive version? Anyone keen to write an iteration version that is shorter than a recursive version ?
Truth is that in this case (factorial) an iterative approach would be better (both faster and cheaper) than a recursive one. It's also true that there are many cases where people use recursion even if iteration works better. I believe the reason is that recursive code is more readable and closer to how a human would solve the problem intuitively. However there are also cases where recursion practically is the only choice (e.g. quicksort, ackerman function etc...)