java - 这个递归阶乘函数中的乘法何时完成?

标签 java math recursion stack

我试图理解以下问题:

public class Main {
    public static int fact(int n){
        if (n == 0){
            return 1;
        }else{
            return n * fact(n - 1);
        }
    }
    public static void main(String[] args){
      System.out.print(fact(5));
    }
}

当编译器执行 return n * fact(n - 1); 时它实际上乘以 n或者它只在到达基本情况后才执行此操作,然后将堆栈中存储的所有值相乘?

注意我对这种递归编码方式仍然很陌生。

最佳答案

查看乘法执行顺序的好方法是将 n *fact(...) 替换为 mult(n,fact(...)),其中 mult 是您编写的方法,它接受两个数字并返回它们的乘积。然后,您可以在 mult 中添加一些输出打印,并查看调用的顺序。

public class FactorialExample {
    // The new mult method.
    private static int mult( final int x, final int y ) {
        System.out.println( "Multiplying "+x+" and "+y+"." );
        return x * y;
    }

    public static int fact(int n){
        if (n == 0){
            return 1;
        }else{
            return mult(n, fact(n - 1)); // using the new mult method
        }
    }

    public static void main(String[] args){
      System.out.print(fact(5));
    }
}

这会产生以下输出:

Multiplying 1 and 1.
Multiplying 2 and 1.
Multiplying 3 and 2.
Multiplying 4 and 6.
Multiplying 5 and 24.
120

回想一下,左加数是对应于 n 的加数,并且对 fact第一次调用具有最大值。因此,递归调用 fact(4) 必须首先完成(生成 24),然后将 524 相乘。

关于java - 这个递归阶乘函数中的乘法何时完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19579520/

相关文章:

Java Out Of Band(称为 "urgent data")数据

java - 如何将音频剪辑转换为数组以执行FFT?

javascript - 我将如何在 Canvas 上旋转图像以面向其运动方向?

c++ - 计算文件的熵

javascript - Math.Random 无法正常工作 typescript

java - 递归方法行为怪异

Java 输出编号行格式

java - 如何使用自签名证书从 Javascript 连接到 SSL 服务器?

c++ - 为什么我在递归删除目录时遇到问题?

matlab - 在 Matlab 中声明函数递归序列