Calcule la secuencia de Fibonacci en tiempo logarítmico

En anticipación al inicio del curso básico  "Matemáticas para la ciencia de datos", lo invitamos a inscribirse para una lección de demostración gratuita, que será impartida por nuestros expertos.

Y ahora mismo ofrecemos la traducción de un artículo útil.


. , . ? .

?

, 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

, .

, , :

El producto de cualquier matriz y la matriz identidad es igual a la matriz misma, y ​​viceversa, como se muestra arriba.
, , .



, :

Tal matriz (en el centro) se llama matriz de permutación.
( ) .

, 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