Cod sursa(job #988569)

Utilizator vgabi94Vaduva Gabriel vgabi94 Data 23 august 2013 11:54:27
Problema Al k-lea termen Fibonacci Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>
using namespace std;

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

class Matrice   // 2 x 2
{
public:
    Matrice(int64_t a, int64_t b, int64_t c, int64_t d)
    {
        this->a = a; this->b = b;
        this->c = c; this->d = d;
    }
    Matrice() : Matrice(0, 0, 0, 0) {}
    Matrice(int64_t a, int64_t b) : Matrice(a, b, 0, 0) {}
    Matrice operator*(const Matrice&) const;
    Matrice operator%(int64_t) const;
    Matrice operator=(const Matrice&);
    int64_t GetNthFib() const { return b; }
private:
    int64_t a; int64_t b;
    int64_t c; int64_t d;
};

auto Matrice::operator*(const Matrice& op) const -> Matrice
{ return Matrice(a*op.a + b*op.c, a*op.b + b*op.d, c*op.a + d*op.c, c*op.b + d*op.d); }

auto Matrice::operator%(int64_t k) const -> Matrice
{ return Matrice(a % k, b % k, c % k, d % k); }

auto Matrice::operator=(const Matrice& op) -> Matrice
{
    a = op.a; b = op.b; c = op.c; d = op.d;
    return *this;
}

const Matrice M1(0, 1);
const Matrice Z(0, 1, 1, 1);
const int mod = 666013;

Matrice power(int p)
{
    Matrice c;
    if (p == 1)
        return Z;
    else
    {
        if (p % 2 == 0)
        {
            c = power(p / 2);
            return (c * c) % mod;
        }
        else
        {
            c = power(p - 1);
            return (Z * c) % mod;
        }
    }
}

int main()
{
    int K;
    in >> K;
    out << (M1 * power(K-1)).GetNthFib();
    return 0;
}