Matrix Multiplication (& Quick Power)
Description
求 n^n 最右边(就是个位)的数。
Type
Quick Power
Analysis
因为 n 很大,所以不能单纯地去计算后求解。
题目相当于求 n^n % 10 的结果,
所以就是经典的 n^k % m的快速幂问题。
// HDOJ 1061
// Rightmost Digit
// by A Code Rabbit
#include <cstdio>
const int MOD = 10;
template <typename T>
T QuickPower(T rdx, int exp, int mod) {
T res = rdx %= mod;
exp--;
while (exp) {
if (exp & 1) res = res * rdx % mod;
exp >>= 1;
rdx = rdx * rdx % mod;
}
return res;
}
int n;
int main() {
int tot_case;
scanf("%d", &tot_case);
while (tot_case--) {
scanf("%d", &n);
int ans = QuickPower(n, n, MOD);
printf("%d\n", ans);
}
return 0;
}