Given a positive integer N, you should output the most right digit of N^N.
Input
The input contains several test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow.
Each test case contains a single positive integer N(1<=N<=1,000,000,000).
Output
For each test case, you should output the rightmost digit of N^N.
Sample Input
2
3
4
Sample Output
7
6
Hint
In the first case, 3 * 3 * 3 = 27, so the rightmost digit is 7.
In the second case, 4 * 4 * 4 * 4 = 256, so the rightmost digit is 6.
一个类似于快速幂的题目,求N的N次方的个位数,相当于只对个位数求高次幂,利用快速幂的思想,可以进行化简,不然会超时。
涉及到快速幂的思想,就是利用幂的关系进行化简,当幂为偶数时可以把底数化为平方然后将幂除以二,如果幂为奇数就提出一个底数然后再当作偶数进行化简,直到幂为0时结束。
AC代码:
#include<stdio.h>
long long digital(long long a,long long b)
{
long long ans=1;
while(b)
{
if(b%2==1)
ans=(ans*a)%10;
a=(a*a)%10;
b/=2;
}
return ans;
}
int main()
{
long long n,m;
scanf("%I64d",&n);
while(n--)
{
scanf("%I64d",&m);
printf("%I64d\n",digital(m,m));
}
return 0;
}