In your function, factorial_cal, you do almost nothing !
Mathmatically, we have the recursive definition :
0!=1
n!=n*(n-1)!
this way, your recursive function would probably work better like this
int fact_cal(int n)
{
if (n<2)
{
return 1;
}
else
return (n*fact_cal(n-1));
}
}
But an iterative function is much more effective ! and costs less memory.
We have
n!=1*2*3*...*n
so
int fact(n)
{
int i,res=1;
for (i=1;i<n+1;i++)
{
res=res*i;
}
return res;
}
By the way, I would probably use an unsigned long int instead of an int
since n! is always positive and grows very fast. The only issue is that you
don't check for an illegal value of n (negative for example, which returns
1 instead of an undefined result).
Moreover, if there is an effective algorithm to calculate the Euler Gamma
function on C\{-N}, I would be very interested.
MPStarix
At 20:26 06/12/2000 +0000, you wrote:
>Hi friends,
>
>I have just started learning C++ (i'm using a material from
>Cprogramming.com). I've tried to write a program to recursively calculate
>the factorial of a number but it doesn't work. Can someone please tell me
>what i've done wrong, Here is the code:
>
>#include <iostream.h>
>#include <stdlib.h>
>
>int factorial_cal(int results)
>{
> if (results>0)
>
> results=1*results;
> factorial_cal(results-1);
>
> return results;
>}
>int main()
>
>{
>int number;
>int results;
>cout<< "Enter a number for me to caculate its Factorial"<<endl;
>cin>>number;
>results=number;
>factorial_cal(results);
>
>cout<< " The factorial of "<<number<< " is "<<results<<endl;
>
> system("PAUSE");
> return 0;
>}
>
>_______________________________________________
>Dev-cpp-users mailing list
>Dev...@li...
>http://lists.sourceforge.net/mailman/listinfo/dev-cpp-users
|