Cod sursa(job #2618240)

Utilizator matthriscuMatt . matthriscu Data 23 mai 2020 22:35:26
Problema Al k-lea termen Fibonacci Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <fstream>
#include <cmath>

struct Matrix {
    int m[2][2];

    Matrix(int a, int b, int c, int d) {
        m[0][0] = a;
        m[0][1] = b;
        m[1][0] = c;
        m[1][1] = d;
    }

    Matrix() {
       m[0][0] = m[0][1] = m[1][0] = m[1][1] = 0;
    }

    friend Matrix operator * (Matrix A, Matrix B) {
        return Matrix(  A.m[0][0] * B.m[0][0] + A.m[0][1] * B.m[1][0],
                        A.m[0][0] * B.m[0][1] + A.m[0][1] * B.m[1][1],
                        A.m[1][0] * B.m[0][0] + A.m[1][1] * B.m[1][0],
                        A.m[1][0] * B.m[0][1] + A.m[1][1] * B.m[1][1]);
    }
};

int main() {
    int n, i, p2;
    std::ifstream fin("kfib.in");
    std::ofstream fout("kfib.out");
    fin >> n;
    p2 = (int)log2(n);
    Matrix v[32], rez(1, 0, 0, 1);
    v[0] = Matrix(1, 1, 1, 0);
    for(i = 1; i <= p2; ++i)
        v[i] = v[i-1] * v[i-1];

    while(n) {
        rez = rez * v[p2];
        n -= (1 << p2);
        p2 = (int)log2(n);
    }
    fout << rez.m[0][0];
}