Home > Net >  Why doesn't the 'Fibonacci number' code stop?
Why doesn't the 'Fibonacci number' code stop?

Time:11-07

I came across such an example of solving the problem.:

public class Fibonacci {
    int fib(int n) {
        if (n < 2)
            return 1;
        return (fib(n - 2)   fib(n - 1));

        }
    }

    public static void main(String[] args) {
        int n = 17711;
        for (int i = 0; i < n; i  )
            print((new Fibonacci()).fib(i));

    }
}

Expected Result - display numbers Fibonacci until to n.

CodePudding user response:

It will finish eventually, but the way you've designed your code will do 217711 operations, which will definitely take at least until the heat death of the universe.

You will not be able to calculate such high Fibonacci numbers with the way you've designed it. You could save results in an array or use an iterative algorithm instead, which would work much, much faster.

  • Related