对着算法导论上写不行,因为导论上默认b对应二进制存入数组中
但实际上取不出来,所以需要移位操作,会想到用向左移位,每次恰好读的是最高位
但这样是错误的,因为左移等价于乘以2,所以这个数一直在增长,直到超出数据范围变为负值才会结束
所以应该采用右移位
对应的代码如下:
#include <iostream>
using namespace std;
int mod_exp(long long a, long long b, long long n) {
int ans = 1;
while(b) {
if(b & 1)
ans = ans*a %n;
a = a*a%n;
b >>= 1;
}
return ans%n;
}
int main(void) {
long long a, n, b, c;
cin >> n;
while(n--) {
cin >> a;
cout << mod_exp(a, a, 10) << endl;
}
return 0;
}
数据类型采用int时,需要cout << mod_exp(a%10, a, 10) << endl;
不然会WA掉,我猜是给出的数据大小超出了int