题目链接:a^b
解题思路:
- 快速幂模版
- 位运算的应用
常规解法及其问题
- 超时:b的上界是 1 9 1^9 19,而1s的范围大约是 1 8 1^8 18,所以在极限条件下,程序会超时
- 超过int的范围:如果a足够大,那么 a * a的范围会超过int所能表示的最大范围就 2 32 − 1 2 ^{32} - 1 232−1
#include<iostream>
using namespace std;
int main(){
int a, b, p;
cin >> a >> b >> p;
for(int i = 1; i < b ; i++){
a = a * a;
}
cout << a % p;
return 0;
}
优化解法:
- 快速幂:一种计算
a^b % p
的算法,包含位运算的应用 - 防止溢出:乘以一个
1ll
,实现隐式类型转换来实现避免内存的溢出
#include<iostream>
using namespace std;
int main(){
int a, b, p;
cin >> a>> b>> p;
int res = 1 % p;
while(b){
if(b & 1){//b的最后一位是1的情况
res = res * 1ll * a % p;
}
a = a * 1ll * a % p;
b = b >> 1;
}
cout << res << endl;
return 0;
}
题目链接:增加模数
解题思路:
- 对每一个指数都用快速幂进行计算
- 快速幂的模版
- 超时的解决方法:用scanf替代cin,去进行读入操作
#include<iostream>
#include<cstdio>
using namespace std;
int t, m, h;
long long a, b;
int main(){
scanf("%d", &t);
while(t--){
scanf("%d", &m);// 模的数字
scanf("%d", &h);
long long res = 0;
while(h--){//h组数字
scanf("%d%d", &a, &b);
long long ans = 1 % m;
while(b){
if(b & 1){
ans = ans * a % m;
}
a = a * a % m;
b = b >> 1;
}
res = (res + ans) % m;
}
cout << res <<endl;
}
return 0;
}
题目链接:64位整数乘法
#include<iostream>
#include<cstdio>
using namespace std;
typedef unsigned long long ULL;//定义常量 方便使用
ULL a, b, p;
int main(){
cin >> a >> b >> p;
ULL res = 0;
while(b){
if(b & 1){
res = (res + a) % p;
}
b = b >> 1;
a = a * 2 % p;// * 2等价于 + a
}
cout << res << endl;
return 0;
}