如果我将递归调用除以另一个递归调用,会得到一个无限循环吗?

huangapple go评论77阅读模式
英文:

If I divide a recursive call by another, would I get an infinite loop?

问题

以下是您要求的翻译部分:

我正在尝试在Java中使用递归,并且我有这个方法:

public static int recursion(int n) {
    if(n==1) {
        return 2;
    } else {
        int test = (recursion(n-1))/(recursion(n-1));
        return test;
    }
}

如果我使用 n = 50 运行它,它从不打印任何内容,所以我猜递归调用是无限的?有人能解释一下为什么吗?

英文:

I'm experimenting with recursion in Java and I have this method:

public static int recursion(int n) {
    if(n==1) {
        return 2;
    } else {
        int test = (recursion(n-1))/(recursion(n-1));
        return test;
    }
}

If I run it with n = 50, it never prints anything, so I'm guessing the recursive calls are infinite? Could anybody explain why?

答案1

得分: 12

这不是无限的,只是非常大。您将进行大约2^50次递归调用。即使每次调用只需要一纳秒(这远远低于实际情况),这意味着总运行时间约为两周左右。

英文:

It is not infinite, just huge. You will do roughly 2^50 recursive calls. Even if each call takes just one nanosecond (which is much too low) this means a total run time of about two weeks.

答案2

得分: 8

在这里,recursion() 被调用就像一个二叉树一样:

recursion(50) -> recursion(49) -> recursion(48) ...
                                  recursion(48) ...
                 recursion(49) -> recursion(48) ...
                                  recursion(48) ...

因此,二叉树的高度为49。
然后 recursion() 被调用:树的节点总数次。这等于 2^(h+1)-1 = 2^(49+1)-1 = 2^(50)-1 次。
这是一个巨大的数量,需要很长时间才能执行完。这就是问题所在,但并不是无限的。

相反地,你可以采用以下方式,这不会产生问题,因为 recursion(n)recursion(n-1) 只被调用一次:

public static int recursion(int n) {
    if(n==1) {
        return 2;
    } else {
        int test = recursion(n-1);
        test = test/test
        return test;
    }
}
英文:

Here, recursion() is called like a binary tree

recursion(50) -> recursion(49) -> recursion(48) ...
                                  recursion(48) ...
                 recursion(49) -> recursion(48) ...
                                  recursion(48) ...

So the binary tree height is 49.
Then recursion() is called: total number of nodes of the tree times. This equates to 2^(h+1)-1 = 2^(49+1)-1 = 2^(50)-1 times.
That's huge, which takes a very long time to execute. This is the problem, but it's not infinite.

You can instead do the following, which is not a problem because recursion(n) to recursion(n-1) is called only once:

public static int recursion(int n) {
    if(n==1) {
        return 2;
    } else {
        int test = recursion(n-1);
        test = test/test
        return test;
    }
}

huangapple
  • 本文由 发表于 2020年10月11日 12:19:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64300561.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定