Cod sursa(job #2293865)

Utilizator dey44andIoja Andrei-Iosif dey44and Data 1 decembrie 2018 17:39:57
Problema Al k-lea termen Fibonacci Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>

#define MATRIX_SIZE 5
#define MODULO 666013
#define input "kfib.in"
#define output "kfib.out"

using namespace std;

ifstream in(input);
ofstream out(output);

class matrix
{
	public:
		unsigned long long table[MATRIX_SIZE][MATRIX_SIZE], N, M;
};

matrix operator*(matrix a, matrix b)
{
	matrix c;
	for (int i = 1; i <= a.N; i++)
	for (int j = 1; j <= b.M; j++)
	{
		c.table[i][j] = 0;
		for (int k = 1; k <= a.M; k++)
		{
			int rez = (a.table[i][k] * b.table[k][j]) % MODULO;
			c.table[i][j] = (c.table[i][j] + rez) % MODULO;
		}
	}
	c.N = a.N, c.M = b.M;
	return c;
}

matrix logarithm_power_rec(matrix base, int power)
{
	if (power == 1) return base;
	if (power % 2) return base * logarithm_power_rec(base, power - 1);
	return logarithm_power_rec(base * base, power / 2);
}

matrix logarithm_power(matrix base, int power)
{
	matrix res = base, baza = base;
	power--;
	while (power > 0)
	{
		if (power % 2) power--, res = res * baza;
		else power /= 2, baza = baza * baza;
	}
	return res;
}

void Solve_Problem()
{
	int matrix_power;
	in >> matrix_power;
	matrix FIBO, Z;
	FIBO.N = 1, FIBO.M = 2, FIBO.table[1][1] = 0, FIBO.table[1][2] = 1;
	Z.N = 2, Z.M = 2, Z.table[1][1] = 0, Z.table[1][2] = 1, Z.table[2][1] = 1, Z.table[2][2] = 1;
	Z = logarithm_power(Z, matrix_power - 1);
	FIBO = FIBO * Z;
	out << FIBO.table[1][2] << "\n";
}


int main()
{
	Solve_Problem();
	return 0;
}