快速幂
数字太大可以把int换成long long试一试
#include<bits/stdc++.h>
using namespace std;
int PowMod(int a, int b){
int ans = 1;
while (b) {
if (b & 1)
ans = (ans*a);
a = (a*a);
b >>= 1;
}
return ans;
}
int a, b, c;
int main() {
cin >> a >> b;
cout << a << "^" << b << " = " << PowMod(a, b);
return 0;
}
快速幂取余
#include<bits/stdc++.h>
using namespace std;
int PowMod(int a, int b, int c){
int ans = 1;
a %= c;
while (b) {
if (b & 1)
ans = (ans*a)%c;
a = (a*a)%c;
b >>= 1;
}
return ans;
}
int a, b, c;
int main() {
cin >> a >> b >> c;
if (a == c) {//特判相等情况
cout<<a<<"^"<<b<<" mod "<<c<<"="<<'0'<<endl;
return 0;
}
cout << a << "^" << b << " mod " << c << "=" << PowMod(a, b, c);
return 0;
}
快乘
`#include<bits/stdc++.h>
using namespace std;
int MUL(int a, int b){
int ans = 0;
while (b) {
if (b & 1)
ans = (ans+a);
a = (a*2);
b >>= 1;
}
return ans;
}
int a, b, c;
int main() {
cin >> a >> b;
cout << a << "^" << b << " = " << MUL(a, b);
return 0;
}`