I've attempted memoization of a recursive Fibonacci method, and it returns the correct number. However, it doesn't appear any faster than before. I'm assuming that this is because I'm not utilizing the array properly to keep track and I'm still making redundant calls. Can you please tell me what to change so I can use it properly?
Not sure if it matters, but fibIndex[]
is declared in the global area, and set to a length of [index + 1] in the main method after getting the input.
public static BigInteger fibRec(int index)
{
BigInteger results;
if (index <= 2)
{
results = BigInteger.ONE;
}
else
{
if (fibIndex[index] != null)
{
results = fibIndex[index];
}
else
{
results = fibRec(index - 1).add(fibRec(index - 2));
}
}
return results;
}