Sorry to post this code again. Previously the issue was I got a stack overflow error which was fixed by using long instead of int. However for a big value of n, I got a Exception in thread "main" java.lang.OutOfMemoryError: Java heap space. Question:
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.
My Code:
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) ;
}
}
}
Since I have to add to the sum of the previous numbers, I will end up Exception in thread "main" java.lang.OutOfMemoryError: Java heap space for a huge value of n. I know the hashtable is suppose to assist in speeding up the calculations. How do I make sure that my recursion method, printSyra can return the value early if it has encountered an element that I have calculated before using the HashMap.
Driver Code:
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
? – Tomasz Nurkiewicz Oct 7 '12 at 16:49getStoreValue()
with the sameindex
argument twice - so you never really use cached values insyraSumHashTable
... – Tomasz Nurkiewicz Oct 7 '12 at 17:28