Cod sursa(job #1455723)

Utilizator fluture.godlikeGafton Mihnea Alexandru fluture.godlike Data 28 iunie 2015 22:34:45
Problema Al k-lea termen Fibonacci Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <cstdio>
#define MOD 666013

FILE *fin, *fout;
using namespace std;
int n;
struct matrice
{
    int a[2][2];
} tmp, aux;
matrice inmultire(matrice temp1, matrice temp2)
{
    matrice sol;
    for(int i = 0; i< 2; i++)
    {
        for(int j = 0; j< 2; j++)
        {
            sol.a[i][j] = 0;
            for(int k = 0; k< 2; k++)
            {
                sol.a[i][j] = (sol.a[i][j] + 1LL*temp1.a[i][k]*temp2.a[k][j])%MOD;
            }
        }
    }
    return sol;
}
matrice power(matrice temp1, int b)
{
    matrice sol, temp2;
    sol.a[0][0] = 1;
    sol.a[0][1] = 0;
    sol.a[1][0] = 0;
    sol.a[1][1] = 1;
    for(; b; b>>=1)
    {
        if(b&1)
        {
            temp2 = inmultire(sol, temp1);
            sol = temp2;
        }
        temp2 = inmultire(temp1, temp1);
        temp1 = temp2;
    }
    return sol;
}
int main()
{
    fin = freopen("kfib.in", "r", stdin);
    fout = freopen("kfib.out", "w", stdout);
    tmp.a[0][0] = 0;
    tmp.a[0][1] = 1;
    tmp.a[1][0] = 1;
    tmp.a[1][1] = 1;
    scanf("%d", &n);
    if(n == 0) printf("0\n");
    if(n == 1) printf("1\n");
    if(n>1)
    {
        aux = power(tmp, n-1);
        printf("%d\n", aux.a[1][1]);
    }
    fclose(fin);
    fclose(fout);
    return 0;
}