Hi guys, I'm totally stucked in this question just as I was about to reach the solution....

Here goes the question:

Given a positive integer n, prints out the sum of the lengths of the Syracuse sequences 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.

It will usually take a long time to calculate the sum of lengths of the syracuse sequence when its input value n is greater than 500 000. To make it faster we can take advantage of the fact that there is considerable overlap between many sequences.

For example: if we have already calculated lengths(3) then we must have computed the sequence:

3 10 5 16 8 4 2 1

and would, threfore, also have had access to answers to lengths(10),lengths(5), lengths(16),lengths(8),lengths(4),lengths(2), and lengths(1). If we can store at least some of these temporary solutions as we go, and then use them, when possible, then the speed of lengths is greatly increased.

In a file called SyraLengthsEfficient.java write a new version of lengths that behaves the same way as the lengths from question two above, but is able to work much faster for large numbers by

memorising some partial solutions.

This new syraLength and it's encapsulating class must contain the code necessary to remember and recall the values of some intermediate lengths.

My solution :

I used a combination of for-loop and addition to try to retrieve the values from my hashmap and add the previous computed length onto my lengthSum, so I used .intValue() to convert Integer to int but I still get NullPointerExceptionCode:

import java.util.HashMap;

import java.util.Map;

import java.util.TreeMap;

public class SyraLengthsEfficient {

HashMap<Integer, Integer> memory = new HashMap<Integer, Integer>();

// Map<Integer, Integer> memory = new TreeMap<Integer, Integer>();

public int lengths(int n)throws IllegalArgumentException

{

int lengthSum = 0;

// If n is less than 1, throw an IllegalArgumentException

if(n < 1)

{

throw new IllegalArgumentException();

}else{

// Otherwise, call the helper method, syra

for(int i=0;i<=n;i++)

{

if(memory.get(n)==null)

{

memory.put(n,syra(n,1)).intValue();

lengthSum+=memory.get(n).intValue();

} else {

lengthSum+=memory.get(n).intValue();

}

}

return lengthSum;

}

}

private int syra(int n, int length)

{

// If n becomes 1, return the length of the Syracuse sequence.

if(n==1)

{

return length;

// If n is even, return syra(n/2, ++length)

} else if(n%2 == 0){

return syra(n/2, ++length);

// If n is odd, return syra(n/2, ++length)

} else {

return syra((n*3)+1, ++length);

}

}

}