无法理解递归的结果

时间:2014-11-13 16:40:38

标签: java recursion

我有代码:

public static void main(String[] args) {
        System.out.println(f(4));

    }

    public static int f(int n){
        if(n == 1) return 1;

        return n / f(n - 1);
    }

为什么这段代码返回4?

2 个答案:

答案 0 :(得分:1)

f(1)将明确返回1

f(2)会给2/f(1)==2/1==2

f(3)会提供3/f(2)==3/2==1int division

f(4)会给4/f(3)==4/1==4

答案 1 :(得分:0)

f(4) -> 4/f(3)
f(3) -> 3/f(2)
f(2) -> 2/f(2)
f(1) -> 1

代替值

f(2) -> 2/1 => 2
f(3) -> 3/2 => 1 (since the return value is 1, 1.5 will be converted to 1)
f(4) -> 4/1 => 4