一/ 快速指数(快速幂)
求 ,base为底数,a为指数。
基本思想:对分治:
可以把a分解成二进制数
代码基本框架
#include<iostream>
using namespace std;
typedef long long int LL;
LL poww(LL base, LL a);
int main()
{
cout << poww(3, 20) << endl;
return 0;
}
便于理解的函数定义
LL poww(LL base, LL a) {
LL ans = 1;
while (a != 0) {
if (a & 1) ans *= base; // a&1 相当于a%2==1,加快运算
base *= base;
a >>= 1; // 相当于a/=2,加快运算
}
return ans;
}
便于记忆的函数定义
LL poww(LL base, LL a) {
LL ans = 1;
for (; a; base *= base, a >>= 1)
if (a & 1) ans *= base;
return ans;
}
二/ 模指数运算
代码基本框架
#include<iostream>
using namespace std;
typedef long long int LL;
//LL poww(LL base, LL a);
LL poww(LL base, LL a, LL md);
int main()
{
//cout << poww(3, 20) << endl;
cout << poww(7, 256,13) << endl;
return 0;
}
其实和前面求快速幂大同小异。
便于理解的函数定义
LL poww(LL base, LL a,LL md) {
LL ans = 1;
while (a != 0) {
if (a & 1) ans =ans* base%md;
base = base*base%md;
a >>= 1;
}
return ans;
}
便于记忆的函数定义
LL poww(LL base, LL a, LL md) {
LL ans = 1;
for (; a; base = base * base % md, a >>= 1)
if (a & 1) ans = ans * base % md;
return ans;
}