2012-10-07 114 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; 
} 
相關問題