[洛谷P5091]【模板】欧拉定理

题目大意:求$a^b\bmod m(a\leqslant10^9,m\leqslant10^6,b\leqslant10^{2\times10^7})$

题解:扩展欧拉定理:
$$
a^b\equiv
\begin{cases}
a^{b\bmod{\varphi(p)}} &(a,b)=1\\
a^b &(a,b)\not=1,b<\varphi(p)\\
a^{b\bmod{\varphi(p)}+\varphi(p)} &(a,p)\not=1,b\geqslant\varphi(p)
\end{cases}
\pmod{p}
$$
可以求出$\varphi(m)$,然后快速幂即可

卡点:

 

C++ Code:

#include <cstdio>
#include <cmath>
#include <cctype>
int a, mod, phi, b;
namespace Math {
	int Phi(int n) {
		int t = std::sqrt(n), res = n;
		for (int i = 2; i <= t; i++) if (n % i == 0) {
			res = res / i * (i - 1);
			while (n % i == 0) n /= i;
		}
		if (n > 1) res = res / n * (n - 1);
		return res;
	}
	inline int pw(int base, int p) {
		int res = 1;
		for (; p; p >>= 1, base = static_cast<long long> (base) * base % mod) if (p & 1) res = static_cast<long long> (res) * base % mod;
		return res;
	}
}

int read() {
	int ch, x, c = 0;
	while (isspace(ch = getchar()));
	for (x = ch & 15; isdigit(ch = getchar()); ) {
		x = x * 10 + (ch & 15);
		if (x >= phi) x %= phi, c = phi;
	}
	return x + c;
}
int main() {
	scanf("%d%d", &a, &mod);
	phi = Math::Phi(mod);
	b = read();
	printf("%d\n", Math::pw(a, b));
	return 0;
}

  

posted @ 2018-12-13 14:53  Memory_of_winter  阅读(142)  评论(0编辑  收藏  举报