递归问题,因为线程挂起

我在Java中玩了一些练习问题。我为下面给出的程序编写了一个递归程序。我的解决方案是正确的,除了挂起(我相信)恢复到活动状态并更改递归方法的值。我还在调试模式下添加了 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));

    }

}

 


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


函数式编程
浏览 51回答 2
2回答

宝慕林4294392

你的代码是错误的,你应该有return&nbsp;getSqrtCount(sqrt,&nbsp;count);而不是getSqrtCount(sqrt,&nbsp;count);否则,递归是毫无意义的,你完全忽略了递归的结果。

繁星淼淼

您的递归是错误的,因为 在任何情况下,或者即使它深入到递归调用中,也会返回 的值。Java是按值传递的,这意味着修改方法内部的基元的值在该方法之外将不可见。为了纠正这一点,我们可以编写以下递归:count01private int getSqrtCount(Double value) {&nbsp; &nbsp; final Double sqrt = Math.sqrt(value);&nbsp; &nbsp; if((sqrt > 2) && (sqrt % 1 == 0)) {&nbsp; &nbsp; &nbsp; &nbsp; return getSqrtCount(sqrt) + 1;&nbsp; &nbsp; }&nbsp; &nbsp; return 0;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java