Recursion Tutorial

我与影子孤独终老i 提交于 2019-12-25 02:55:47

问题


I am learning Java from a book, and come across a chapter regarding recursion using a factorial example.

//A simple example of recursion

package tutorials;

class Factorial {
// this is a recursive method
int fact (int n) {
    int result;

    if(n==1) return 1;
    result = fact(n - 1) * n;
    return result;
  }
}

class Recursion {
    public static void main(String args[]) {
        Factorial f = new Factorial();

        System.out.println("Factorial of 3 is " + f.fact(3));
        System.out.println("Factorial of 4 is " + f.fact(4));
        System.out.println("Factorial of 5 is " + f.fact(5));
    }
}

The result this piece of code gives is "Factorial of 3 is 6" and "Factorial of 4 is 24"

What i don't understand is what is happening in the class Factorial and why *n is not calculated immediately. The book does not do a very good job of explaining this so i thought i would ask any experienced programmers for help.


回答1:


If you invoke fact(5), here is how it will work:

fact(5)
    5*fact(4)
        4*fact(3)
            3*fact(2)
                2*fact(1)
                    2*1=2 //(since if n==1, 1 is returned directly
                result=2
            result=3*2
        result=4*3*2
    result=5*4*3*2
result=120

Recursion simply means you invoke a method within itself, usually after manipulating the argument to suit your end result (n - 1 in this case). You also make sure you define a terminal condition (n==1 in this case). Internally, the variables are pushed on to a stack to be remembered for every invocation, but that's probably a discussion for another day




回答2:


The factorial of a number n is defined as: n * (n - 1) * (n - 2) * ... * 1 , meaning multiply n by all the positive integers less than n. In you example this is simply reversed, so you first calculate the factorial of n - 1 and then multiply it by n. Continuing this recursion you calculate the factorial of n - 2, n - 3 and so on, until you have to calculate the factorial of 1. In this case you simply return 1 itself and go back into the recursion chain calculating the factorials for 2, 3, ... n - 1, n.



来源:https://stackoverflow.com/questions/30247958/recursion-tutorial

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