Fibonacci Sequence in Java taking too long?

前端 未结 6 900
余生分开走
余生分开走 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:08

    first, use a long instead of an int, to avoid overflow.

    Secondly, use a non-recursive algorithm, as a recursive one exists in exponential time I think. A well designed non-recursive one will solve in linear time (I think).

    Example non-recursive

    static long getSum(int n){
    
        long[] fibonacci = new long[n];
        fibonacci[0] = 1;
        fibonacci[1] = 1;
    
        if (n==0) return 0;
        if (n==1 || n==2) return 1;
    
        for(int i = 2; i < n;i++){
            fibonacci[i] = fibonacci[i-1]+ finonacci[i-2];
        }
        return fibonacci[n-1];
    }
    

    I haven't tested this, but it should work.

    If you plan to call this method frequently, it might be prudent to store the array outside of the method, so that it is a simple lookup when doing this. This would provide a constant time solution for numbers that have already been calculated at least once. an example of that is below.

    static long[] fibonacci= {1,1};
    static long getSum(int n){
    
        if (n==0) return 0;
        if (n==1 || n==2) return 1;
    
        int old_length = fibonacci.length;
    
        if(fibonacci.length < (n-1)){
            fibonacci = Arrays.copyOf(fibonacci,n);
        }else{
            return fibonacci[n-1];
        }
    
    
    
        for(int i = old_length; i < n;i++){
            fibonacci[i] = fibonacci[i-1]+ finonacci[i-2];
        }
        return fibonacci[n-1];
    }
    

    Again, the example is untested, so a bit of debugging might be required.

    Here is a linear time implementation of the algorithm that uses a constant overhead, instead of linear overhead.

    static long getSum(int n){
    
        long currentNum = 0;
        long previousNum = 1;
        long previousNum2 = 1;
    
        if (n==0) return 0;
        if (n==1 || n==2) return 1;
    
        for(int i = 2; i < n;i++){
            currentNum = previousNum+ previousNum2;
            previousNum2 = previousNum;
            previousNum = currentNum;
        }
        return currentNum;
    }
    

提交回复
热议问题