0

抱歉再次发布此代码。以前的问题是我遇到了堆栈溢出错误,该错误通过使用 long 而不是 int 得到了修复。但是对于较大的 n 值,我在线程“main”java.lang.OutOfMemoryError: Java heap space 中遇到异常。问题:

Given a positive integer n, prints out the sum of the lengths of the Syracuse 
sequence starting in the range of 1 to n inclusive. So, for example, the call:
lengths(3)
will return the the combined length of the sequences:
1
2 1
3 10 5 16 8 4 2 1 
which is the value: 11. lengths must throw an IllegalArgumentException if 
its input value is less than one.

我的代码:

  import java.util.*;


  public class Test {

HashMap<Long,Integer> syraSumHashTable = new HashMap<Long,Integer>();

public Test(){

}

public int lengths(long n)throws IllegalArgumentException{

    int sum =0;

    if(n < 1){
        throw new IllegalArgumentException("Error!! Invalid Input!");
    }   

    else{

        for(int i=1;i<=n;i++){
            sum+=getStoreValue(i);
        }
        return sum;


    }


}

private int getStoreValue(long index){
    int result = 0;

    if(!syraSumHashTable.containsKey(index)){
        syraSumHashTable.put(index, printSyra(index,1));
    }

    result = (Integer)syraSumHashTable.get(index);

     return result;

}

public static int printSyra(long num, int count) {
    if (num == 1) {
        return count;
    }
    if(num%2==0){

        return printSyra(num/2, ++count);
    }

    else{

        return printSyra((num*3)+1, ++count) ;

    }
}


}

由于我必须将前面的数字相加,因此我将在线程“main”java.lang.OutOfMemoryError: Java heap space for a huge value of n 中结束异常。我知道哈希表应该有助于加快计算速度。如果我的递归方法 printSyra 遇到了我在使用 HashMap 之前计算过的元素,我如何确保它可以提前返回该值。

驱动程序代码:

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Test t1 = new Test();
    System.out.println(t1.lengths(90090249));

    //System.out.println(t1.lengths(3));
}
4

1 回答 1

0

您需要使用迭代方法而不是递归。该递归方法将对线程的堆栈跟踪产生压力。

public static int printSyra(long num, int count) {
    if (num == 1) {
        return count;
    }

    while (true) {
            if (num == 1) break; else if (num%2 == 0) {num /= 2; count++;) else {num = (num*3) + 1; count++;} 
    }
    return count;
}
于 2012-10-07T18:16:47.950 回答