Could someone explain how this code works?

1 次查看(过去 30 天)
So, we were given this as an example of recursion. It's a program that computes the factorial of a given scalar.
function f = factorial(x)
temp = 0;
if (x == 1)
temp = 1;
else
temp = x*factorial(x-1);
end
I get that x is inputted and if it's value is 0, then it returns 1 right off the bat. However, if x is not equal to 1 then the operation temp = x * factorial(x - 1); is carried out. So, x - 1 is then passed to factorial(), this is where I'm lost. What happens now? How does the value of temp not end up as 0, seeing as it's reset to that at the beginning of the function? Also, how does the code know when to stop and return the result?
f = temp;

采纳的回答

Cedric
Cedric 2013-10-10
编辑:Cedric 2013-10-11
The line
temp = 0 ;
is useless, and the temp which appear afterwards should be f, the output argument.
Hint: consider all "instances" of the factorial function as different, and draw a schematics, e.g.
x = factorial(3)
-> factorial, x=3 [1st instance]
| ..
| else
| f = x * factorial(3-1)
| -> factorial, x=2 [2nd instance]
| | ..
| | else
| | f = x * factorial(2-1)
| | -> factorial, x=1 [3rd in.]
| | | if x == 1
| | | f = 1 ;
| | <-
| | so f = 2 * 1
| <-
| so f = 3 * 2
so x = 6
EDIT: I just realized that there was a typo that you spotted!
This was not
factorial(3 - 2)
but
factorial(3 - 1)
Thank you, I made the correction.
  7 个评论
David
David 2013-10-12
That's a brilliant explanation. Completely get it now. Thank you!

请先登录,再进行评论。

更多回答(1 个)

Youssef  Khmou
Youssef Khmou 2013-10-10
David, The variable temp is local (inside the function), as long as the iterative variable x didnt arrive at 1 the process continues, "temp" is set only inside function , N=4 :
inside func insde func
N=4 -> (Temp=0,..,Temp=3)-->N=3 (Temp=0,Temp=2) .....N=1
  2 个评论
David
David 2013-10-10
Think I've got it now. So the value of factorial(x - 1) is calculated and multiplied by x and calculated again over and over again until x == 1? Temp is specific to each iteration of factorial()? Thanks!

请先登录,再进行评论。

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by