Factorial!
http://www.animatedrecursion.com/
<!-- begin content -->Perhaps the simplest example of recursion is the factorial function. In mathematical notation factorial is represented by the symbol !
Factorial can be defined as follows:
0! = 1,
n! = n(n-1)! for n > 0
This function is said to be defined recursively. The first condition needed for recursion definition is the base case. This is the point at which the recursive calls will stop. In the factorial example this will be when zero factorial (0!) is reached.
So for all cardinals greater than zero the problem of finding factorial is reduced to finding the factorial of a smaller number and then multiplying. This process of breaking the factorial problem down into finding a smaller factorial and multiplying until the smaller number is 0, i.e. the base case where the function does not make another call to itself but instead returns one. Using the Java applet on this page you can step through the factorial algorithm at work.
- In area A the Java source code for the recursive algorithm
used to find the factorial is displayed. As the algorithm executes
the current line of execution is highlighted. - This animation shows pictorially how this algorithm finds
the factorial of a given number. Each time that a recursive call
is made by the algorithm in A the animation is updated thus animating the
action of the algorithm. Each time a recursive call is made a green box
is appended showing the problem faced by that recursive call. When
the base case is reached (i.e. the factorial of 1) the recursive calls
begin to return values this is animated by displaying the amount returned
and by changing the colour of a box signifying a returned call to red. - This is the the levels of recursion. This bar graph
shows the current level of recursion, (i.e. the number of recursive calls
on the stack) - Gives a textual explanation of the line currently under
execution in A. Use the speed control bar (E) to slow down the algorithm
so that you can read each message and follow the "code walk through" at
your own pace. - This speed control allows you to speed up and slow down the
rate at which the algorithm executes. - Here you can enter an integer value to find the factorial.
Notice that when a value of greater than 21 is entered the factorial calculated
is a large negative number, can you explain why this might be?
本文通过阶乘函数的实例介绍了递归的基本概念及其工作原理。文章详细解释了递归定义中的基例,并通过Java小程序直观展示了如何计算阶乘,帮助读者理解递归调用的过程。
522

被折叠的 条评论
为什么被折叠?



