很抱歉再次发布此代码。以前问题是我遇到了堆栈溢出错误,这是通过使用long而不是int来修复的。但是对于n的大值,我在线程“main”中得到了一个异常java.lang.OutOfMemoryError:Java堆空间。 问题:
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堆空间的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 :(得分: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;
}