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 6HintIn 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 0 这个地方千万不要忘记0的存在,因为会有20^201 12 2 4 8 63 3 9 7 14 4 65 56 67 7 9 3 18 8 4 2 69 9 1下面先上一份比较容易理解的代码,用枚举法列出所有可能的情况:#include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> #include<ctype.h> int main() { int T,n; scanf("%d",&T); while(T--) { scanf("%d",&n); if(n == 0) return 0; if(n % 10 == 0) printf("0\n"); if(n % 10 == 1) printf("1\n"); if(n % 10 == 2) { if(n % 4 == 0) printf("6\n"); if(n % 4 == 1) printf("2\n"); if(n % 4 == 2) printf("4\n"); if(n % 4 == 3) printf("8\n"); } if(n % 10 == 3) { if(n % 4 == 0) printf("1\n"); if(n % 4 == 1) printf("3\n"); if(n % 4 == 2) printf("9\n"); if(n % 4 == 3) printf("7\n"); } if(n % 10 == 4) { if(n % 2 == 0) printf("6\n"); if(n % 2 == 1) printf("4\n"); } if(n % 10 == 5) { printf("5\n"); } if(n % 10 == 6) { printf("6\n"); } if(n % 10 == 7) { if(n % 4 == 0) printf("1\n"); if(n % 4 == 1) printf("7\n"); if(n % 4 == 2) printf("9\n"); if(n % 4 == 3) printf("3\n"); } if(n % 10 == 8) { if(n % 4 == 0) printf("6\n"); if(n % 4 == 1) printf("8\n"); if(n % 4 == 2) printf("4\n"); if(n % 4 == 3) printf("2\n"); } if(n % 10 == 9) { if(n % 2 == 0) printf("1\n"); if(n % 2 == 1) printf("9\n"); } } return 0; }
下面说另外一种解题思路:因为只是最后一位有用,所以只把最后一位提取出来。#include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> #include<ctype.h> int main() { int T,n,m,k,i,s; scanf("%d",&T); while(T--) { scanf("%d",&n); m = n % 4; //因为最多四个一循环,所以取4的余 k = n % 10; if(m == 0) //如果n为0的话,相当于是最后一个,无法进行后面的乘法循环,所以变为4 m = 4; s = 1; for(i = 0;i < m;i++) { s = s * n % 10; } printf("%d\n",s); } return 0; }