【模板】快速幂

核心思想:

每一步都把指数分成两半,而相应的底数做平方运算,最后求出的幂结果实际上就是在变化过程中所有当指数为奇数时底数的乘积。

题目跳转

代码

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
uint8_t buf[1<<20],*p1,*p2;
#define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)
ll rd(){
	ll x=0,f=1,ch=gc();
	while(ch<'0'||ch>'9'){
		if(ch=='-'){
            f=-1;
        }
        ch=gc();
	}
	while(ch>='0'&&ch<='9'){
		x=(x<<1)+(x<<3)+(ch-'0');
		ch=gc();
	}
	return x*f;
}
void write(ll x){
	if(x<0){
		x*=-1;
		putchar('-');
	}
	if(x>9){
		write(x/10);
	}
	putchar(x%10+'0');
}
ll x,y,p;
ll ksm(ll x,ll y){
	ll res=1;
	while(y){
		if(y&1){//当指数为奇数时 
			res=res*x%p;
		}
		y>>=1;//指数缩为一半 
		x=x*x%p;
	}
	return res;
}
int main(){
	x=rd();
	y=rd();
	p=rd();
	write(x);
	putchar('^');
	write(y);
	printf(" mod ");
	write(p);
	putchar('=');
	write(ksm(x,y));
	return 0;
}
posted @ 2026-10-17 16:25  beiciqi  阅读(10)  评论(0)    收藏  举报