java - Java阶乘程序中的递归

标签 java recursion

我对递归的了解是函数调用自身 并且它具有停止的基本条件。我的教授写了一个程序,他说程序中发生了递归,我说不,不是。我对此感到困惑。所以我请你消除我的困惑。他制作的程序代码如下:

int fact(int n) {
    if (n == 0) {
        return 1;
    }

    for (int i = n; i >= 1; i--) {
        s1.push(i);
    }
    return Return_result();

}

int Return_result() {
    int f = 1;
    while (s1.top != -1) {
        f = f * s1.pop();
    }
    return f;
}

最佳答案

你是对的,所提供的代码中没有递归。这是一种迭代方法。

递归是,如果在 f() 方法(在 Java 命名法中)或函数(通常)中,您有一个对 f() 的调用。

递归方法如下所示:

int fact(int n) {
    return (n <= 1) ? 1 : fact(n - 1) * n;
}

或者,使用 tail-recursion (也称为“尾调用”):

int fact(int n) {
    return factTail(n, 1);
}

int factTail(int n, int accumulator) {
    return (n <= 1) ? accumulator : factTail(n - 1, n * accumulator);
}

目前,JVM 不执行尾递归优化,但是 this can change :

It's important to note that this isn't a bug in the JVM. It's an optimization that can be implemented to help functional programmers who use recursion, which is much more common and normal in those languages. I recently spoke to Brian Goetz at Oracle about this optimization, and he said that it's on a list of things to be added to the JVM, but it's just not a high-priority item. For now, it's best to make this optimization yourself, if you can, by avoiding deeply recursive functions when coding a functional language on the JVM.

关于java - Java阶乘程序中的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26817849/

相关文章:

java - Android 自定义 ListView 仅显示 Firebase 数据库中的一项

java - 如何迭代我自己实现的队列?

java - 制作可点击的色谱来存储这些点击的 RGB 值

c - Realloc 在目录/文件名的递归存储期间咀嚼字符串数组

c# - 从 DataTable 填充 WinForms TreeView

Java 多态性 : How can I avoid type casting input parameters?

java - 将监听器添加到 SpanElement

recursion - Cypress 中的递归函数存在问题。测试随着时间的推移而减慢

python - 排序()返回无

java - 求三角形中的最大和