Cod sursa(job #961653)

Utilizator mvcl3Marian Iacob mvcl3 Data 12 iunie 2013 18:10:58
Problema Al k-lea termen Fibonacci Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <fstream>
#define MODULO 666013
using namespace std;

ifstream f("kfib.in");  ofstream g("kfib.out");

inline void multiply(int F[2][2], int M[2][2])
{
    int x = ((F[0][0] * M[0][0]) % MODULO + (F[0][1] * M[1][0]) % MODULO) % MODULO;
    int y = ((F[0][0] * M[0][1]) % MODULO + (F[0][1] * M[1][1]) % MODULO) % MODULO;
    int z = ((F[1][0] * M[0][0]) % MODULO + (F[1][1] * M[1][0]) % MODULO) % MODULO;
    int w = ((F[1][0] * M[0][1]) % MODULO + (F[1][1] * M[1][1]) % MODULO) % MODULO;

    F[0][0] = x;
    F[0][1] = y;
    F[1][0] = z;
    F[1][1] = w;
}

inline void power(int F[2][2], int m)
{
    int M[2][2] = {{1,1}, {1, 0}};

    for(int i = 2; i <= m; ++i)
        multiply(F, M);
}

inline int fib(int k)
{
    if(k == 0) return 0;

    int F[2][2] = {{1, 1}, {1, 0}};
    power(F, k - 1);

    return F[0][0];
}
int main()
{
    int n;

    f >> n;
    g << fib(n) << '\n';

    g.close();
    return 0;
}