题目:
Rightmost Digit
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 85186 Accepted Submission(s): 31372
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).
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.
Author
Ignatius.L
题意:求n的n次方的个位数,n最大有1000000000(明显要找规律)
题解:求个位数实际就是n的个位数相乘,这个规律不难找1,5,6,0无论多少个相乘都是自身,4奇数个相乘个位为4,偶数个为6,9对应9,1,其次2,3,7,8都有int a[5][5] = { {2,4,8,6}, {3,9,7,1},{7,9,3,1},{8,4,2,6}};,再总结一下就是四个一循环(公共最小公倍数如1,1,1,1也算四个一循环)
代码1(笨办法,分情况讨论,细节要处理好):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int a[5][5] = {
{2,4,8,6}, {3,9,7,1},{7,9,3,1},{8,4,2,6}};
int main()
{
int t, i, j, ans, n, m;
scanf("%d", &t);
while(t--){
scanf("%d", &m);
n = m%10;
if(n==6||n==1||n==5||n==0){
ans = n;
}
if(n==4||n==9){
i = m%2; //一直w,后来发现我这个地方搞错了,之前一直用的n,也就是取余后的数,难受
if(i==0){
if(n==4) ans = 6;
if(n==9) ans = 1;
} else{
ans = n;
}
}
if(n==2||n==3||n==7||n==8){
if(n==2) i=0;
if(n==3) i=1;
if(n==7) i=2;
if(n==8) i=3;
j = (m-1)%4;
ans = a[i][j];
}
printf("%d\n", ans);
}
return 0;
}
代码2(四个一循环):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main()
{
int t, i, j, ans, n;
scanf("%d", &t);
while(t--){
scanf("%d", &n);
i = n%4;
n = n%10;
if(i==0) i = 4;
ans = (int)pow(n,i)%10;
printf("%d\n",ans);
}
return 0;
}