3

I am trying to make use of a cache to improve the performance of my Fibonacci method. However, it is still taking a lot of time to compute even fibonacci(40).

import java.util.Scanner;
public class FibWithCache {

    public static void main(String args[]) {
        System.out.println("Enter Fibonacci index: ");
        Scanner sc = new Scanner(System.in);
        int index = sc.nextInt();
        sc.close();

        System.out.println(fibonacci(index));
    }

    private static long fibonacci(int index) {

        long result = 0;
        long[] fibCache = new long[200];

        if(index==0)
            return 0;
        else if(index == 1)
            return 1;
        else if(fibCache[index] != 0)
            return fibCache[index];
        else {
            result = fibonacci(index-1) + fibonacci(index-2);
            fibCache[index] = result;
            return result;
        }
    }
}

Why am I unable to benefit from the cache?

0

3 Answers 3

12

Hint: The issue is that each recursive call to fibonacci() has its own cache. For every call you create an empty cache, store something in it, and immediately discard it.

What you want is one cache shared by all the calls.

I'll let you figure out how best to do it. :)

Sign up to request clarification or add additional context in comments.

1 Comment

I declared the array in the class and it worked. Thanks a lot
3

There should only be one instance to fibCache (it has to be static).

Comments

1
public class FibonacciCache {

    private int[] cache = new int[1000];
    
    public FibonacciCache(){
        // n de 1 = 1;
        cache[1] = 1;
    }

    public int fibonacciDe(int n){
        if(cache[n] != 0){
            return cache[n];
        }
    
        // n de 0 = 0
        if(n <= 0){
            return 0;
        }
                        
        int result = fibonacciDe(n-1) + fibonacciDe(n-2);
        cache[n] = result;
        return result;
    }

1 Comment

Can you edit your answer to explain why and how this code can reply to the question ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.