Problem solution | "algorithm contest Step-up Guide" a ^ b

【topic】

Find a value of the b-th power modulo p, wherein 0 a , b , p 1 0 9 0 \leq a,b,p \leq 10^9

【answer】

Because the number is too large, or whether it is time accuracy is not enough, so starting a fast power. Namely the use of a b = ( a a . . . ) ( b / 2 ) a^b = (a*a*...)^{\left(b/2\right)} , for example: 3 4 = 9 2 3^4 = 9^2 , 2 5 = 4 2 2 2^5 = 4^2*2 . Simplify a b a^b course, to be noted that in the case where p = 0.

time complexity: O ( l o g N ) O (lie)

#include<iostream>
#include<cstring>
#include<sstream>
#include<string>
#include<cstdio>
#include<cctype>
#include<vector>
#include<queue>
#include<cmath>
#include<stack>
#include<list>
#include<set>
#include<map>
#include<algorithm>
#define fi first
#define se second
#define MP make_pair
#define P pair<int,int>
#define PLL pair<ll,ll>
#define lc (p<<1)
#define rc (p<<1|1)	
#define MID (tree[p].l+tree[p].r)>>1
#define Sca(x) scanf("%d",&x)
#define Sca2(x,y) scanf("%d%d",&x,&y)
#define Sca3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define Scl(x) scanf("%lld",&x)
#define Scl2(x,y) scanf("%lld%lld",&x,&y)
#define Scl3(x,y,z) scanf("%lld%lld%lld",&x,&y,&z)
#define Pri(x) printf("%d\n",x)
#define Prl(x) printf("%lld\n",x)
#define For(i,x,y) for(int i=x;i<=y;i++)
#define _For(i,x,y) for(int i=x;i>=y;i--)
#define FAST_IO std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define STOP system("pause")
#define ll long long
const int INF=0x3f3f3f3f;
const ll INFL=0x3f3f3f3f3f3f3f3f;
const double Pi = acos(-1.0);
using namespace std;
template <class T>void tomax(T&a,T b){ a=max(a,b); }  
template <class T>void tomin(T&a,T b){ a=min(a,b); }
ll qpow(ll a,ll k,int MOD){
	ll sum = 1%MOD;
	a%=MOD;
	while(k){
		if(k&1) sum = (sum*a)%MOD;
		a = (a*a)%MOD;
		k>>=1;
	}
	return sum;
}

int main(){
	int a,b,mode;
	scanf("%d%d%d",&a,&b,&mode);
	Prl(qpow(a,b,mode));
} 
Published 39 original articles · won praise 9 · views 1962

Guess you like

Origin blog.csdn.net/qq_36296888/article/details/103057561