2012-10-07 3 views
0

이 코드를 다시 게시하여 죄송합니다. 이전에 문제는 int 대신 long을 사용하여 수정 된 스택 오버플로 오류가 발생했습니다. 그러나 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와 : 자바 거대한 n 값을위한 힙 공간. 해시 테이블이 계산 속도를 높이는 데 도움이된다고 알고 있습니다. HashMap을 사용하기 전에 계산 한 요소가 있으면 재귀 메소드 인 printSyra가 값을 일찍 반환 할 수 있는지 확인하려면 어떻게해야합니까?

드라이버 코드 :

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; 
} 
관련 문제