主要从1.2.4来讲这一方面
Rightmost Digit |
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) |
Total Submission(s): 4541 Accepted Submission(s): 1190 |
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
Hint
In the first case, 3 * 3 * 3 = 27, so the rightmost digit is 7.
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的个位数;而n的取值范围为1<=N<=1,000,000,000; 如果利用for循环直接求得n^n;最后在取余。这样对小数据(1,2,3...)可以求出,但对于大数据无疑可能超时,或者超过数据范围而导致出错,(因此要选好数据结构)。此时就应该要从内部寻找规律。 |
首先不管是小数据还是大数据,因只需管个位数,因为最后的个位数就是各位数相乘所得。其次:
对于1,1^n的个位数始终为1;2,2^n(1,2,3,4....)的个位数分别是2,4,8,6,2,4,8,6....以4为周期的2,4,8,6,同理,3^n是以4为周期的3,9,7,1.....可以得到i的周期以及里面的元素:
a[10][10] = {{1, 0},{1, 1},{4, 2,4,8,6},{4, 3,9,7,1},{2, 4,6},{1, 5},{1, 6},{4, 7,9,3,1},{4, 8,4,2,6},{2, 9,1}};然后对于任意输入的n,首先可以先求得其个位数m,得到个位数的周期a[m][0];然后利用周期求得n在周期的第几个r=n%a[m][0],(需要注意的是若r=0;则应令r=a[m][0]),
便可以求到n^n的个位数。
ps: 1,对于n组数据,可以利用while(n--) {};更加简便
2,对于一些小数据正确大数据错误的题目要注意是否有规律
3,数据的定义应当放在输入的前面,否则容易导致无法编译(oj中一定多加注意,可能编译器可以编译,oj不行)
4,一般数据定义在main函数第一层,(少放在循环内)更加方便使用,不用再考虑循环时值是否改变,需要重新赋值。(如下题的i,f)
答案如下:
#include <stdio.h> int main(void) { int t,n,i,f; int a[10][10] = {{1,0},{1,1},{4,2,4,8,6},{4,3,9,7,1},{2,4,6},{1,5},{1,6},{4,7,9,3,1},{4,8,4,2,6},{2,9,1}}; scanf("%d", &t); while(t--) { scanf("%d", &n); f=n%10; i=n%a[f][0]; if(i==0) i=a[f][0]; printf("%d\n",a[f][i]); } return 0; }