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.
当时一看题以为是快速幂,然后一直wa,后来学长讲才知道要用快速乘或者说是(龟速乘)
之所以不单纯的用快速幂是因为(**1 ≤ a, b, c < 263)**a,b,c都非常大,都是long long 类型的,
先看下面的普通的快速幂
ll quick_mi(ll a,ll b,ll c)
{
ll ans=1;
ll p=a;
while(b)
{
if(b&1)
{
ans=ans*p%c;//注意这条语句,ans*p 因为c是long long ,所以这些数都可能是long long 的,再乘的话可能溢出
}
p= p*p;//这个地方也是如此
b=b>>1;
}
return ans%c;
}
所以这个地方不能直接乘,要再写一个函数
原理
20* 14比如说太大了,会溢出,那就分解14,分解成二进制(1110),相当于20*(0+2+4+6),我们不想用乘法,
20* 2就相当于(20+20)%c
20* 4就相当于(40+40)%c
20* 6就相当于(80+80)%c
这样就不会溢出了
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#include<map>
#include<string>
using namespace std;
#define ll long long
ll a,b,c;
ll quick_cheng(ll a1, ll a2 )//快速乘
{
ll sum=0;
ll q=a2;
while(a1)
{
if(a1&1)
{
sum=(sum+q)%c;
}
q=(q+q)%c;
a1=a1>>1;
}
return sum%c;
}
ll quick_mi()
{
ll ans=1;
ll p=a;
while(b)
{
if(b&1)
{
ans=quick_cheng(ans,p);
}
p= quick_cheng(p,p);
b=b>>1;
}
return ans%c;
}
int main()
{
while(scanf("%lld%lld%lld",&a,&b,&c)!=EOF)
{
printf("%lld\n",quick_mi());
}
return 0;
}