跳到正文

题解

P1226 题解

ikunTLE约 1 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 1 分钟
题目
P1226

版本

  1. v1当前

题目传送门

暴力解法

循环 bb 次,每一次答案乘 aa。但是时间复杂度 O(b)O(b) 无法通过。

快速幂

考虑对 bb 进行二进制拆位,这一点基于幂的一个性质 Xu×Xv=Xu+vX^u\times X^v=X^{u+v}。

所以 aba^b

注意事项

  • 运算时注意开 long long。
  • 注意需要取模。

AC CODE

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
int read(){int x=0;char f=1,ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();return x*f;}
int q_pow(int a,int b,int MOD){
	int res=1;
	while(b){
		if(b&1)
			res=res*a%MOD;
		b>>=1;
		a=a*a%MOD;
	}
	return res;
}
signed main(){
	int a=read(),b=read(),p=read();
	printf("%lld^%lld mod %lld=%lld",a,b,p,q_pow(a,b,p));
	return 0;
}
原文