快速幂模板

(b^p)%k
递归版 :

#include<iostream>
#include<cstdio>
#define ll long long
using namespace std;
inline void read(ll &x){
	int f=1;
	x=0;
	char 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();
	}
	x*=f; 
}
inline ll quick_pow(ll b,ll p,ll k){
        if(p==0) return 1;
	if(p==1) return b; 
	ll res=quick_pow(b,p>>1,k);
	res=res%k*res%k;
	if(p%2==1) res=res%k*b%k;
	return res%k;
}
int main(){
	ll a,b,c;
	read(a);read(b);read(c);
	printf("%lld^%lld mod %lld=",a,b,c);
	printf("%lld",quick_pow(a,b,c)%c);
	return 0;
} 

非递归版 :

#include<iostream>
#include<cstdio>
#define ll long long
using namespace std;
inline void read(ll &x){
	int f=1;
	x=0;
	char 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();
	}
	x*=f; 
}
inline ll quick_power(ll b,ll p,ll k){
	ll ans=1;	//结果 
	while(p>0){
		if(p&1) ans=ans*b%k;	//p&1 == p%2==1
		b=b*b%k;
		p>>=1;	 //p>>=1 == p/2;
	}
	return ans;
}
int main(){
	ll a,b,c;
	read(a);read(b);read(c);
	printf("%lld",quick_power(a,b,c)%c);      //输出时必须%c,要不然会报错
	return 0;
} 
原文地址:https://www.cnblogs.com/-pwl/p/13693077.html