.
, :
factorial(0) = 1
factorial(n) = n * factorial(n-1)
, .
The recursive version and recursive relation defined above look the same and therefore easier to read.
Recursive:
double factorial ( int n )
{
return ( n ? n * factorial ( n-1 ) : 1 );
}
Cycle:
double factorial ( int n )
{
double result = 1;
while ( n > 1 )
{
result = result * n;
n--;
}
return result;
}
One more thing:
The recursive version of the factorial includes a tail call for itself and can be optimized using a tail call. This brings the spatial complexity of the recursive factorial up to the spatial complexity of the iterative factorial.
source
share