Cod sursa(job #1059902)

Utilizator mikeshadowIon Complot mikeshadow Data 17 decembrie 2013 10:40:15
Problema Al k-lea termen Fibonacci Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <string.h>

#define min(a,b) ((a<b)?a:b)
#define max(a,b) ((a<b)?b:a)
#define abs(a) ((a<0)?-a:a)

#define INF 1000001

using namespace std;


#ifndef TEST
ifstream fin ("kfib.in");
ofstream fout ("kfib.out");
#else
ifstream fin ("input.txt");
ofstream fout ("output.txt");
#endif

#define REP(i,a,b) \
    for (int i=a; i<=b; i++)

#define MAXN 100000

#define MOD 666013
typedef long long ll;

struct mat
{
    ll x[2][2];
};

mat con;

mat prod(mat a, mat b)
{
    mat t;
    t.x[0][0] = a.x[0][0]*b.x[0][0]+a.x[1][0]*b.x[0][1];
    t.x[0][0]=t.x[0][0]%MOD;
    t.x[1][0] = a.x[0][0]*b.x[1][0]+a.x[1][0]*b.x[1][1];
    t.x[1][0]=t.x[1][0]%MOD;
    t.x[0][1] = a.x[0][1]*b.x[0][0]+a.x[1][1]*b.x[0][1];
    t.x[0][1]=t.x[0][1]%MOD;
    t.x[1][1] = a.x[0][1]*b.x[1][0]+a.x[1][1]*b.x[1][1];
    t.x[1][1]=t.x[1][1]%MOD;
    return t;
}

mat power(mat x, int n)
{
    if (n<=0)
    {
        mat t;
        t.x[0][0]=1;
        t.x[1][0]=0;
        t.x[0][1]=0;
        t.x[1][1]=1;
        return t;
    } else if (n==1) return x;
    if (n%2)
    {
        mat t;
        t = power(x,n/2);
        return prod(x,  prod( t,t));
    } else
    {
        mat t;
        t = power(x,n/2);
        return prod(t,t);
    }
}

int main()
{
    int k;
    fin>>k;

    mat t;
    t.x[0][0]=0;
    t.x[1][0]=1;
    t.x[0][1]=0;
    t.x[1][1]=0;
    con.x[0][0]=0;
    con.x[1][0]=1;
    con.x[0][1]=1;
    con.x[1][1]=1;
    ll rez;
    if (k)
    {
        t = prod (t, power(con,k-2));
        rez = t.x[0][0]+t.x[1][0];
    } else rez=0;
    rez = rez%MOD;
    fout<<rez;

    return 0;
}