Cod sursa(job #2891003)

Utilizator cristiemanuelstroe cristian emanuel cristiemanuel Data 17 aprilie 2022 12:43:11
Problema Ridicare la putere in timp logaritmic Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
/* Exponentiere binara (ridicare la putere in timp logaritmic)
 *
 * Dorim sa calculam x^n % Mod in complexitate O(log2(n))
 *
 * x^n = x^(n/2) * x^(n/2)      daca n par
 *     = x^(n/2) * x^(n/2) * x  daca n impar
 *
 * Pow(x, n) = Pow(x, n / 2) * Pow(x, n / 2)        daca n par
 *           = Pow(x, n / 2) * Pow(x, n / 2) * x    daca n impar
 */
#include <iostream>
using namespace std;

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

const int Mod = 1999999973;

int Pow(int x, int n) // O(log2(n))
{
	if (n == 0) return 1;

	int res = Pow(x, n / 2);
	cout<<res<<' ';

	// res = (1LL * res * res) % Mod;
	res = ((long long)res * res) % Mod;
	if (n % 2 == 1)
		res = (1LL * res * x) % Mod;

	return res;
}

int main()
{
	int x, n;
	in >> x >> n;

	out << Pow(x, n) % Mod;

	return 0;
}