英文:
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;
    }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论