Cod sursa(job #3209654)

Utilizator AnSeDraAndrei Sebastian Dragulescu AnSeDra Data 3 martie 2024 11:08:03
Problema Al k-lea termen Fibonacci Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>

using namespace std;

const int MOD = 666013;
const int Matrix_Size = 2;

typedef long long matrix[Matrix_Size][Matrix_Size];

matrix unitate = {{1, 0}, {0, 1}};
matrix recurenta_fib = {{1, 1}, {1, 0}};

void inmultire(matrix dest, matrix a, matrix b){
    for(int lin = 0; lin < Matrix_Size; lin++){
        for(int col = 0; col < Matrix_Size; col++){
            dest[lin][col] = 0;

            for(int i = 0; i < Matrix_Size; i++){
                dest[lin][col] += a[lin][i] * b[i][col];
            }

            dest[lin][col] %= MOD;
        }
    }
}

void copiaza(matrix from, matrix to){
    for(int i = 0; i < Matrix_Size; i++){
        for(int j = 0; j < Matrix_Size; j++){
            to[i][j] = from[i][j];
        }
    }
}

void inmulteste_si_atribuie(matrix ans, matrix other){
    matrix aux;

    inmultire(aux, ans, other);
    copiaza(aux, ans);
}

int lgput(matrix element, int exp){
    matrix sol;

    copiaza(unitate, sol);

    while(exp){
        if(exp & 1){
            inmulteste_si_atribuie(sol, element);
        }

        inmulteste_si_atribuie(element, element);
        copiaza(aux, element);
        exp >>= 1;
    }

    return sol[0][0];
}

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

    int n, first_element;

    fin >> n;

    first_element = 1;

    fout << first_element * lgput(recurenta_fib, n - 1);

    return 0;
}