**
Problem Description
找出一種有效的方法來計算 a^n( mod m) 的值,其中a, n爲非負整數,m爲正整數, 且a<1018。
Input Description
可能會有多組,每組輸入滿足題設的三個整數a, n 和 m.
Output Description
對於每組輸入,輸出a^n( mod m) 的值。
Sample Input
2 3 5
0 456 36
12345678901234567 123456789012345 9876543210123456
**
#include<stdio.h>
typedef long long ll;
ll multi(ll a,ll b,ll m) //快速冪//
{
ll exp=a%m,res=0;
while(b)
{
if(b&1)
{
res+=exp;
if(res>=m)res-=m;
}
exp<<=1;
if(exp>m)exp-=m;
b>>=1;
}
return res;
}
ll lg(ll a,ll n,ll m)
{
if(n==0)return 1;
ll ans=lg(a,n>>1,m);
ans=multi(ans,ans,m);
if(n&1)ans=multi(ans,a,m);
return ans;
}
int main()
{
ll a,n,m;
while(~scanf("%lld %lld %lld",&a,&n,&m))
{
printf("%lld\n",lg(a,n,m));
}
return 0;
}