求幂的优化:快速幂+大数相乘取模 = 快速大数幂
快速幂:
在<math.h>的头文件中自带的 pow 函数在调用时需要一系列类型转换,所以数值并不是很严格精确,存在误差,执行效率低,最好不要用,最好自己编写。
ll mypow(ll x, ll n, ll mod) { //ll是long long型
ll res = 1;
while (n > 0) {
if (n & 1) res = res * x % mod;
x = x * x % mod;
n >>= 1;
}
return res;
}
大数乘法取模:
在计算 x * x % mod 和 res * x % mod 时,由于 x 与 res 都会很大,直接相乘可能溢出 long long 的数据范围,此时就需要用大数乘法取模的方法。
ll mymul(ll a, ll b, ll mod) {
a %= mod;
b %= mod;
ll ans = 0;
while (b > 0) {
if (b & 1) {
ans += a;
if (ans >= mod)
ans -= mod;
}
a <<= 1;
if (a >= mod) a = a - mod;
b >>= 1;
}
return ans;
}
eg.
大数乘法
给定a,b,c,要求按照以下程序计算ans:
ans=1
for(i=1;i<=b;i++){
ans=ans*a;
}
ans%=c
输出ans
小明发现这看起来就是大数乘法和大数取模的裸题,但是他忘了怎么写了,请你帮帮他!
Input
多组输入,每组数据一行,每行给出3个正整数a,b,c (1<=a,b,c<=1e18)
Output
每组数据输出一行,为答案
Sample Input
2 10 10000000
5 100 1
0 2 37
Sample Output
1024
0
0
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string.h>
#include<cstdio>
#include<queue>
#include<cmath>
typedef long long ll;
using namespace std;
ll mul(ll a,ll b,ll mod)//大数乘法取模
{
ll ans=0;
while(b>0)
{
if(b&1)
{
ans=(ans+a)%mod;
}
a=(a+a)%mod;
b>>=1;
}
return ans;
}
ll ppow(ll a,ll b,ll mod)//快速幂+大数乘法取模=快速大数幂
{
ll ans=1;
while(b>0)
{
if(b&1)
{
ans=mul(ans,a,mod);
}
a=mul(a,a,mod);
b>>=1;
}
return ans;
}
int main()
{
ll a,b,mod;
while(cin>>a>>b>>mod)
{
cout<<ppow(a,b,mod)<<endl;
}
return 0;
}