2012-10-07 66 views
0

对不起,再次发布此代码。以前的问题是我得到了一个堆栈溢出错误,通过使用long而不是int来修复。然而,对于n的大值,我在线程“main”java.lang.OutOfMemoryError:Java堆空间中得到了异常。 问:java.lang.OutOfMemoryError:Java堆空间和HashMap

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) ; 

    } 
} 


} 

因为我必须添加到先前数的总和,我最终会在线程异常“主要” java.lang.OutOfMemoryError:Java的为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)); 
} 
+0

'syraSumHashTable'的用途是什么? –

+0

我想用它来存储printSyra(n)的计算结果,以便它可以更高效。 –

+2

你觉得它对你有什么帮助?你永远不会使用同样的'index'参数调用'getStoreValue()'两次 - 所以你从来没有真正在'syraSumHashTable'中使用缓存值... –

回答

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; 
} 
相关问题