Cod sursa(job #3295980)

Utilizator mateicrainiceanuMatei Crainiceanu mateicrainiceanu Data 10 mai 2025 12:25:59
Problema Al k-lea termen Fibonacci Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
using namespace std;

#define MOD 666013

int Z[2][2] = {{0, 1}, {1, 1}};

void cp_mat_2x2(int src[2][2], int dest[2][2]) {
    for (int i = 0; i < 2; ++i)
        for (int j = 0; j < 2; ++j)
            dest[i][j] = src[i][j];
}

void mat_mult_2x2(int A[2][2], int B[2][2], int result[2][2]) {
    result[0][0] = (1LL * A[0][0] * B[0][0] + 1LL * A[0][1] * B[1][0]) % MOD;
    result[0][1] = (1LL * A[0][0] * B[0][1] + 1LL * A[0][1] * B[1][1]) % MOD;
    result[1][0] = (1LL * A[1][0] * B[0][0] + 1LL * A[1][1] * B[1][0]) % MOD;
    result[1][1] = (1LL * A[1][0] * B[0][1] + 1LL * A[1][1] * B[1][1]) % MOD;
}

void exponentiation_by_sq(int M[2][2], int p, int result[2][2]) {
    result[0][0] = 1; result[0][1] = 0;
    result[1][0] = 0; result[1][1] = 1;

    int base[2][2];
    cp_mat_2x2(M, base);

    int temp[2][2];

    while (p > 0) {
        if (p % 2 == 1) {
            mat_mult_2x2(result, base, temp);
            cp_mat_2x2(temp, result);
        }
        mat_mult_2x2(base, base, temp);
        cp_mat_2x2(temp, base);
        p /= 2;
    }
}

int main() {

    ifstream fin("kfib.in");
    ofstream fout("kfib.out");

    int k;
    fin >> k;

    int result[2][2];
    exponentiation_by_sq(Z, k, result);
    fout << result[0][1];

    fout.close();
    return 0;
}