This is not doing what you want it to do because on the second iteration you will be way off the index you started with:
first iteration: where a = 6, will return factorial(30);
second iteration: where a = 30, will return factorial(870);
Look at this instead:
1 2 3 4 5 6
long factorial(long a, long f = 0) // one variable to index, one for product
{
if(!f) f = a; // first iteration so set f to a
f *= (--a); // a * (a-1)
return (a > 1) ? factorial(a,f) : f; // if we have 1, return product else keep iterating
}
Good explanation ( Texan40 ) thanks for your help.
-------------------------------------------------------------------------------------
i learn pointer several times is that something like this:
int A ;
int * B ;
int **C ;
B = &A ;
*B = 20;
**C = &B;
(B) is pointed to address of (A ) if assign a value to (B) it assign to the address (A) and toked again
and if you assign a value to the (C) its assigned to address of (B)
in case (A) is Equal To (**C).
It would be a good explanation except it's inaccurate, and there is no reason for a factorial function to take two arguments.
1 2 3 4 5 6 7 8 9 10 11
long factorial (long a)
{
if (a > 1)
{
return (a * factorial (a-1)); // this line..................
}
else
{
return (1);
}
}
Recursion is all about the divide and conquer strategy.
If you call this with a = 6, it will return 6*factorial(5), 5 will return 5*factorial(4) down until you get to 1. the net result is 6*5*4*3*2*1 or the factorial of 6.
However, a factorial function is a very poor candidate for recursion as it is so easily converted into a loop.