1. 程式人生 > >模冪運算

模冪運算

lar brush while 快速 wiki https 方程 fine highlight

  https://en.wikipedia.org/wiki/Modular_exponentiation

  該算法在一些數論題中十分有用。算法用於快速求解同余方程 $ c = a^b \ mod \ M $ ,其中 a, b, M 已知。

  code:

#include <iostream>
#define ll long long
ll modexpo(ll base, ll expo, ll mod)
{
	if (mod == 1) return 0;
	ll res = 1; while (expo > 0)
	{
		if (expo & 1)	res = (res*base) % mod;
		base = (base*base) % mod; expo >>= 1;
	}
	return res;
}
int main()
{
	std::cout << modexpo(2,3,5) << std::endl;
	return 0;
}

  

  

模冪運算