Fibonacci Sequence in Java taking too long?

前端 未结 6 911
余生分开走
余生分开走 2021-01-13 18:44

I\'m trying to find the sum of the Fibonacci sequence in Java, but the run time is taking way too long (or is it suppose to?). This slows down anytime I use an integer past

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-13 19:10

    As the others already stated you should use long for the calculated fibonacci value, as the number will get very long very fast.

    If your formost priority is performance you could use the following formula:


    with

    (Idea taken from Linear Algebra lecture, actual formula taken from Wikipedia.)
    That way you will get the n-th fibonacci number in constant time (depending on the calculation of the n-th powers in the formula).


    The following code calculates the fibonacci sequenc of the first 93 numbers with no waiting time (on my machine):

    private static final double SQRT_FIVE = Math.sqrt(5);
    private static final double GOLDEN_RATIO = (1 + SQRT_FIVE) / 2;
    
    public static void main(String[] args) {
        for(int i = 0; i <= 92; i++) {
            System.out.println("fib(" + i + ") = " + calculateFibonacci(i));
        }
    }
    
    public static long calculateFibonacci(int n) {
        double numerator = Math.pow(GOLDEN_RATIO, n) - Math.pow(1-GOLDEN_RATIO, n);
        double denominator = SQRT_FIVE;
    
        // This cast should in general work, as the result is always an integer. 
        // Floating point errors may occur!
        return (long)(numerator/denominator); 
    }
    

    From the 94-th number on the long is no longer sufficent and you need to use BigInteger and fitting math operations, as the double calculations may produce calculation errors with such big numbers.

提交回复
热议问题