A^B mod C(快速幂+快速乘)
Description:
Given a, b, c find the value of ab mod c (1 ≤ a, b, c < 263).
Input
Contains multiple test cases. Each test is given in one line and contains three integers a, b and c.
Output
For each test case print on a separate line the value of ab mod c.
Example 1
Input example
3 2 4
2 10 1000
Output example
1
24
题解:直接用快速幂数据范围会超过long long(就是底数相乘还没来的及取模就已经超了),所以要用到快速乘把乘法运算化成加法运算,在运算过程中每加一次取一次模就能避免数据超出范围;
AC代码:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <iostream>
using namespace std;
long long fast_mul(long long a,long long b,long long mod)
{
long long ans=0;
while(b)
{
if(b&1)
ans=(ans+a)%mod;
a=(a+a)%mod;
b>>=1;
}
return ans;
}
long long fast_pow(long long a,long long b,long long mod)
{
long long ans=1;
while(b)
{
if(b&1)
ans=fast_mul(ans,a,mod);
a=fast_mul(a,a,mod);
b>>=1;
}
return ans;
}
int main()
{
long long a,b,c;
while(~scanf("%lld%lld%lld",&a,&b,&c))
printf("%lld\n",fast_pow(a,b,c));
return 0;
}