0

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;
}
user207421
  • 305,947
  • 44
  • 307
  • 483

2 Answers2

4

It's not running faster because you are not actually using memoization i.e. you are not putting results in the array. If you don't do that, then your implementation will actually be slower, because you keep checking for memoized results that you never actually memoized. Here's what you need to do.

public static BigInteger fibRec(int index) { 
    if (index <= 2) return BigInteger.ONE;

    BigInteger result = fibIndex[index];
    if (result == null) {
        result = fibRec(index - 1).add(fibRec(index - 2));
        fibIndex[index] = result; // you forgot this
    }
    return result;
}

EDIT: I made a note here earlier about you not needing memoization for a method you call just once, but then I remembered that the method is recursive. So forget what I said here before, memoization will actually speed up the method quite a lot.

Leo Aso
  • 11,898
  • 3
  • 25
  • 46
  • My goodness, what a simple mistake on my part!! Thank you so much. It WAS actually taking longer the higher numbers I was computing. 50 was taking 56 seconds before and is now at .003 seconds! – StartideRising Feb 10 '19 at 22:58
3

I noticed you’re not actually filling in fibIndex anywhere. Based on that, when will your if statement condition trigger?

Does that give you a sense of what to fix?

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • Ah, this helps me understand the other comment better. Since I'm not filling the array, my if statement can't trigger properly because I've always got a null value. That's what Leo Aso means by "checking for memoized results that were never memoized". Thanks, I appreciate it! – StartideRising Feb 10 '19 at 23:05