CH0101 a ^ b fast power

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_45508368/article/details/99095371

Topic Link

http://noi-test.zzstep.com/contest/0x00%E3%80%8C%E5%9F%BA%E6%9C%AC%E7%AE%97%E6%B3%95%E3%80%8D%E4%BE%8B%E9%A2%98/0101%20a%5Eb

analysis

Fast power template, attention intermediate results may overflow, as well as to consider b = 0 , p = 1 b = 0, p = 1 special circumstances.

AC Code

#include <cstdio>

inline int read() {
	int num = 0;
	char c = getchar();
	while (c < '0' || c > '9') c = getchar();
	while (c >= '0' && c <= '9')
		num = num * 10 + c - '0', c = getchar();
	return num;
}

inline int qpow(int a, int b, int p) {
	int ans = 1, x = a % p;
	while (b) {
		if (b & 1) ans = 1ll * ans * x % p;
		x = 1ll * x * x % p, b >>= 1;
	}
	return ans % p;
}

int main() {
	int a = read(), b = read(), p = read();
	printf("%d", qpow(a, b, p));
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45508368/article/details/99095371