AcWing 89. a^b

Topic links: https://www.acwing.com/activity/content/problem/content/323/1/

 

89. a^b

 

Seeking  A A in  B B of the power  p value modulo p.

Input Format

Three integers  A , B , P A, B, P, separated by spaces in the same row.

Output Format

Output an integer representing a^b mod pthe value.

data range

0a,b,p1090≤a,b,p≤109

Sample input:

3 2 7

Sample output:

2

解题思路:
首先暴力的写法是乘一个a然后就对p取一次余,但是这样会超时。
基于二进制的思想,我们可以将b写成一个二进制数,这样我们每对b右移以为就让a乘以自己,并且当b是奇数的时候就将答案乘上一个a同时对p取余数。这样时间复杂度就是logn。这样就不会超时了。
AC代码:
#include <iostream>
#include <cstdio>

using namespace std;

typedef long long LL;

inline int qm(int a, int b, int p) {
	LL res = 1;
	LL tmp = a;
	while(b) {
		if(b & 1) res = (res * tmp) % p;
		tmp = (LL)tmp * tmp % p;
		b >>= 1;
	}
	
	return res;
}

int main(void) {
//	freopen("in.txt", "r", stdin);
	int a, b, p;
	scanf("%d%d%d", &a, &b, &p);
	if(b == 0) printf("%d\n", 1 % p);
	else printf("%d\n", qm(a, b, p));
	return 0;
}

  

 

Guess you like

Origin www.cnblogs.com/phaLQ/p/11460570.html