Is there a better way (performance) calculate fibonacci than this one?

后端 未结 3 707
猫巷女王i
猫巷女王i 2020-12-30 15:59

I made this code.. And I need to get the best of it.. I really need the best performance of calculating fibonacci numbers.. please help be..

I\'ve read some code of

3条回答
  •  抹茶落季
    2020-12-30 16:45

    Your implementation doesn't work for any decent number because it makes the stack overflow.

    I don't see any reason to use recursivity here. Recursivity is pretty but generally heavier (it's language dependent). Here's a working implementation with a simple for loop :

    private static BigInteger[] fibTmp = {BigInteger.ZERO, BigInteger.ONE};
    private static int maxCached = 1;
    public static BigInteger fibonacci(int v) {
        if (fibTmp.length<=v) {
            fibTmp = Arrays.copyOf(fibTmp, v*5/4);
        }
        for (; maxCached

    That's a direct implementation without looking for an efficient Fibonacci algorithm in the literature. You'd better look for them.

    Note also that this cache based implementation is memory costly and makes only sense if you call the function multiple times.

提交回复
热议问题