Factorial!

本文通过阶乘函数的实例介绍了递归的基本概念及其工作原理。文章详细解释了递归定义中的基例,并通过Java小程序直观展示了如何计算阶乘,帮助读者理解递归调用的过程。

Factorial!

http://www.animatedrecursion.com/

<!-- begin content -->
<!--<span class="submitted">Submitted by Anonymous on Wed, 2006-10-18 10:22.</span>-->
<!-- google_ad_section_start -->

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.


  1. 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.
  2. 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.
  3. 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)
  4. 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.
  5. This speed control allows you to speed up and slow down the
    rate at which the algorithm executes.
  6. 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?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值