Topic analysis:
Although only requires pow (x, x)% 10, but quick thinking and seeking power pow (x, y)% mod same.
The former corresponds to a simplified version of the latter.
Problem-solving ideas
- If y is the number 1, the pow (x, 1)% mod = x% mod;
- If an odd number of times y is 2n + 1, can be obtained pow (x, n), pow (x, y) = pow (x, n) * pow (x, n) * x
- If y is an even number 2n, can be determined pow (x, n), pow (x, y) = pow (x, n) * pow (x, n)
The following code (G ++):
#include <bits\stdc++.h>
using namespace std;
typedef long long ll;
ll mod = 10;
//快速幂求pow(x,y)%mod
ll pow_mod(ll x, ll y) {
//若次数y为1,则pow(x,1)%mod = x%mod;
if (y == 1) return x;
//若次数y为奇数2n+1,可求出pow(x,n),pow(x,y) = pow(x,n)*pow(x,n)*x
//若次数y为偶数2n,可求出pow(x,n),pow(x,y) = pow(x,n)*pow(x,n)
ll p = pow_mod(x, y / 2) % mod;
if (y % 2) return (p * p * x) % mod;
else return (p * p) % mod;
}
int main() {
int t;
cin >> t;
while (t--) {
ll n;
cin >> n;
cout << pow_mod(n, n) << endl;
}
return 0;
}