3.djwcb【算法赛】 - 蓝桥云课 (lanqiao.cn)
写了个long long快速幂只过了30%:
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n;
int q_pow(int a, int p) {
int res = 1;
while (p) {
if (p & 1)res = res *a % 10; // 如果 b 是奇数,则将 res 乘以 a 并取模
a = a * a % 10; // 将 a 的平方取模
p >>= 1; // 将 b 右移一位,相当于除以 2
}
return res;
}
signed main()
{
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n;
while (n--)
{
int a, b;
cin >> a >> b;
int res = q_pow(a, b);
cout << res << endl;
}
return 0;
}
因为p最大,太大了,要存字符串存。用string快速幂就全部通过了:
#include<bits/stdc++.h>
using namespace std;
#define int long long
int n;
int q_pow(int x, string p) {
int res = 1;
x %= 10;
for (int i = p.size() - 1; i >= 0; --i) {
int digit = p[i] - '0';
int temp = 1;
for (int j = 0; j < digit; ++j) {
temp = (temp * x) % 10;
}
res = (res * temp) % 10;
x = (x * x) % 10;
}
return res;
}
signed main()
{
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n;
while (n--)
{
int a;
string b;
cin >> a >> b;
int res = q_pow(a, b);
cout << res << endl;
}
return 0;
}