题目地址:http://contest-hunter.org:83/contest/0x00「基本算法」例题/0101 a^b
本题是快速幂,利用二进制的移位与&运算。
注意a=0 与p=1的情况。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
using namespace std;
int quick(int a,int b,int p)
{
int m=1;
if(a==0) m=0;///注意a=0 的时候 m=0
while(b>0)
{
if(b&1)
m=(long long)m*a%p;
b=b>>1;
a=(long long)a*a%p;
}
return m%p;///注意p=1的时候
}
int main()
{
int a,b,p;
scanf("%d%d%d",&a,&b,&p);
//if(p!=1)
// b=b%(p-1);
///注意不是费马小定理
a=quick(a,b,p);
printf("%d\n",a);
return 0;
}