java - 由于线程挂起而导致递归问题

标签 java recursion

我正在用 Java 解决一些练习问题。我为下面给出的程序编写了一个递归程序。我的解决方案是正确的,除了挂起的(我相信)恢复到 Activity 状态并更改递归方法的值之外。我还添加了 Debug模式下 Eclipse 的屏幕截图,其中显示了线程堆栈。

package com.nix.tryout.tests;
/**
 * For given two numbers A and B such that 2 <= A <= B,
 * Find most number of sqrt operations for a given number such that square root of result is a whole number and it is again square rooted until either the 
 * number is less than two or has decimals. 
 * example if A = 6000 and B = 7000, sqrt of 6061 = 81, sqrt of 81 = 9 and sqrt of 9 = 3. Hence, answer is 3
 * 
 * @author nitinramachandran
 *
 */
public class TestTwo {

    public int solution(int A, int B) {
        int count = 0;

        for(int i = B; i > A ; --i) {

            int tempCount = getSqrtCount(Double.valueOf(i), 0);

            if(tempCount > count) {
                count = tempCount; 
            }
        }

        return count;
    }

    // Recursively gets count of square roots where the number is whole
    private int getSqrtCount(Double value, int count) {

        final Double sqrt = Math.sqrt(value);

        if((sqrt > 2) && (sqrt % 1 == 0)) {
            ++count;
            getSqrtCount(sqrt, count);
        }
        return count;
    }

    public static void main(String[] args) {

        TestTwo t2 = new TestTwo();

        System.out.println(t2.solution(6550, 6570));
    }
}

上面的屏幕截图来 self 的调试器,我已经圈出了线程堆栈。任何人都可以尝试运行该程序并让我知道问题是什么以及解决方案是什么?我可以想出一个非递归的解决方案。

最佳答案

你的递归是错误的,因为count的值在任何情况下都会返回01,即使它深入递归来电。 Java 是按值传递的,这意味着修改方法内部原语的值在该方法外部是不可见的。为了纠正这个问题,我们可以编写以下递归:

private int getSqrtCount(Double value) {

    final Double sqrt = Math.sqrt(value);

    if((sqrt > 2) && (sqrt % 1 == 0)) {
        return getSqrtCount(sqrt) + 1;
    }
    return 0;
}

关于java - 由于线程挂起而导致递归问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55326600/

相关文章:

java - 如何知道递归文件扫描的当前文件夹深度

Java枚举和循环问题

java - 如何使用另一个程序编译Java程序?

javascript - 将递归 JS 函数转换为 Obj-C

algorithm - 有人能解释一下如何合并两个二叉树吗?

c++ - 使用递归反转字符串在 C 中有效,但在 C++ 中无效

java - 在 ListView 中使用 XML 布局扩展自定义 View

Haskell 递归类型

c - 如何在C中使用递归打印?

java - 在 Spring Boot 应用程序的应用程序属性文件中使用 Jenkins 变量