【发布时间】:2012-09-28 01:23:06
【问题描述】:
很抱歉再次发布此代码。以前的问题是我得到了一个堆栈溢出错误,该错误是通过使用 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));
}
【问题讨论】:
-
syraSumHashTable的目的是什么? -
我想用它来存储之前 printSyra(n) 的计算结果,这样可以提高效率。
-
您认为它对您有何帮助?您永远不会使用相同的
index参数两次调用getStoreValue()- 所以您永远不会真正使用syraSumHashTable中的缓存值... -
java.lang.OutOfMemoryError - 如果您需要存储大量序列,请使用数据库
-
@TomaszNurkiewicz:是的,我意识到我应该从我的递归方法中调用它。谢谢。
标签: java recursion hashmap out-of-memory