Calculate the Fibonacci sequence in logarithmic time

In anticipation of the start of the basic course  "Mathematics for Data Science", we invite you to sign up for a free demo lesson, which will be conducted by our experts.

And right now we offer translation of a useful article.


. , . ? .

?

, n- . - 1 1. - 2, - 3, 5, 8 . .

?

, . , , ( n-1 n-2).

// calculates nth term of fibonacci, 1 indexed
Procedure Fib_Naive(int n):
    if(n < 3):
        return 1;
        end_if
    return Fib_Naive(n-1) + Fib_Naive(n-2)
end_Fib_Naive

, , , .

(temp) , , , ( , , ).

// calculates nth term of fibonacci, 1 indexed
Procedure Fib(int n):
        if(n < 3): return 1;
        int prev = 1;
        int cur = 1;
        for i = 3...n:
            int temp = cur;
            cur += prev;
            prev = temp;
        end_for
return cur;
end_Fib

, .

, , :

The product of any matrix and the identity matrix is ​​equal to the matrix itself, and vice versa, as shown above.
, , .



, :

Such a matrix (in the center) is called a permutation matrix.
( ) .

, 2x1 (a, b). ? , (a + b).

. ? a ((n-1)-) , b .

.

, n- (0, 1), n- .

?

: . , n , , .

, 8- , , 4- , . , 8 .

, :

, , Java ( , ).

, - , , :

public int fib(int N) {
        if(N == 0) return 0;
        int[] sol = fibHelp(N);
        
        return sol[1];
    }
    
    public int[] fibHelp(int n) {
        if(n == 1) {
            return new int[] {0,1};
        }
        int m = n/2;
        
        int[] temp = fibHelp(m);
        
        int fPrev = temp[0];
        int fCur = temp[1];
        
        int prev = (fPrev * fPrev) + (fCur * fCur);
        int cur = fCur * (2 * fPrev + fCur);
        int next = prev + cur;
        
        if(n % 2 == 0) { 
            return new int[] {prev, cur};
        }
        else {
            return new int[] {cur, next};
        }
    }

*: , , , : .

O(n log(n)). . , .


.




All Articles