Cod sursa(job #771518)

Utilizator space.foldingAdrian Soucup space.folding Data 26 iulie 2012 10:57:17
Problema Al k-lea termen Fibonacci Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include <cstdio>
using namespace std;

struct M2
{
	M2() : x(0LL), y(0LL), z(0LL), t(0LL) { }
	M2(long long x, long long y, long long z, long long t) : x(x), y(y), z(z), t(t) { }
	long long x, y, z, t;
};

void multiply(M2 const & a, M2 const & b, M2 & result, long long mod)
{
	result.x = (a.x * b.x + a.y * b.z) % mod;
	result.y = (a.x * b.y + a.y * b.t) % mod;
	result.z = (a.z * b.x + a.t * b.z) % mod;
	result.t = (a.z * b.y + a.t * b.t) % mod;
}

void multiply(M2 &a, M2 const &b, long long mod)
{
	M2 aux1 = a;
	M2 aux2 = b;
	multiply(aux1, aux2, a, mod);
}


void power(M2 const &whatM, int exp, long long mod, M2 &out)
{
	
	M2 id(1LL,0LL,0LL,1LL), sec(whatM.x, whatM.y, whatM.z, whatM.t);
	out = id;
	while(exp)
	{
		if(exp & 1)
		{
			multiply(out, sec, mod);
		}
		exp >>= 1;
		multiply(sec, sec, mod);
	}
}

int main ()
{
#ifndef ONLINE_JUDGE
	//freopen("kfib.in", "r", stdin);
	//freopen("kfib.out", "w", stdout);
#endif

	M2 A(1,1,1,0), B(1,1,1,0), C;

	int p;

	scanf("%d", &p);

	power(A, p, 666013LL, C);
	printf("%d\n", C.y);

	return 0;
}