Cod sursa(job #1229073)

Utilizator o_micBianca Costin o_mic Data 16 septembrie 2014 12:15:57
Problema Al k-lea termen Fibonacci Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <iostream>
#include <fstream>
#define LL long long

using namespace std;

struct matrix{
    LL a, b, c, d;
};

matrix c, my_unit;

matrix multiply(matrix a, matrix b)
{
    c.a = a.a * b.a + a.b * b.c;
    c.b = a.a * b.b + a.b * b.d;
    c.c = a.c * b.a + a.d * b.c;
    c.d = a.c * b.b + a.d * b.d;
    return c;
}

matrix power(matrix base, LL exponent)
{
    if(exponent == 0)
        return my_unit;
    if(exponent == 1)
        return base;
    if(exponent % 2)
        return multiply(base, power(multiply(base, base), exponent / 2));
    else
        return power(multiply(base, base), exponent / 2);
}

int main()
{
    matrix m, res;
    LL n;
    fstream f("kfib.in", ios::in);
    fstream g("kfib.out", ios::out);
    f >> n;
    my_unit.a = my_unit.d = 1;
    my_unit.b = my_unit.c = 0;
    m.a = 0;
    m.b = m.c = m.d = 1;
    if(n >= 1){
        res = power(m, n-1);
        g << res.d;
    }
    else
        g << 0;
    return 0;
}