Factorial using recursion in C

坚强是说给别人听的谎言 提交于 2019-12-08 12:41:44

问题


We all know the program for this

int fact(int n)
{
  if(n==0)  
    return(1);

  return(n*fact(n-1));
}

But what is not clear to me is how the inner thing is happening?

How is it calculating 5*4*3*2*1 (if n is 5)

Please give a clear explanation on this.

Thanks.....


回答1:


Mathematically, the recursive definition of factorial can be expressed recursively like so (from Wikipedia):

Consider how this works for n = 3, using == to mean equivalence:

3! == 2! * 3 == (1! * 2) * 3 == ((1) * 2) * 3

This can be derived purely symbolically by repeatedly applying the recursive rule.

What this definition does is first expand out a given factorial into an equivalent series of multiplications. It then performs the actual multiplications. The C code you have performs the exact same way.




回答2:


What might help to understand it, is that when you are recursively calling the function, the new "cycle" will use N-1, not N. This way, once you get to N==0, the last function you called will return a 1. At this point all the stack of functions are waiting for the return of the nested function. That is how now you exactly multiply the results of each of the functions on the stack. In other words, you factorize the number given as input.



来源:https://stackoverflow.com/questions/18784343/factorial-using-recursion-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!