Rightmost Digit
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 36 Accepted Submission(s) : 18
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
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~9也就10个数字,固然有规律可循。
这题的规律就是直接用N的 个位数 来求。 而0~9的N次方也是有规律的,Eg :下面分别是N的1~10次方的个位数
0: 0 0 0 0 0 0 0 0 0 0
1: 1 1 1 1 1 1 1 1 1 1
2: 2 4 8 6 2 4 8 6 2 4
3: 9 7 1 3 9 7 1 3 9 7
4: 6 4 6 4 6 4 6 4 6 4
5: 5 5 5 5 5 5 5 5 5 5
6: 6 6 6 6 6 6 6 6 6 6
7: 9 3 1 7 9 3 1 7 9 3
8: 4 2 6 8 4 2 6 8 4 2
9: 9 1 9 1 9 1 9 1 9 1
很明显1~9的递增次方都可以用 4作为周期,求出个位数后,最多再求到4次方就可以得到答案。
代码:
#include<iostream>
using namespace std;
int main()
{
int n,i,j,t,k;
cin>>t;
while(t--)
{
cin>>n;
i=n%10;//记录n的个位数
if(n%4)//以4为周期,做多只求到4次方即可
j=n%4;
else
j=4;
k=1;
for(int l=1;l<=j;l++)
k*=i;//这一步,我用k=(int)pow(i,1.0*j)各种WA,求好心人解答
k%=10;
cout<<k<<endl;
}
return 0;
}