Rightmost Digit
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 38642 Accepted Submission(s): 14558
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. 快速幂的基本应用,特别要注意数据范围,应该使用__int64否则会超时,代码如下:
1 #include2 #include 3 #include 4 #include 5 using namespace std; 6 7 int pow1(int x, int n) 8 { 9 __int64 ans = 1, t = n;10 while(n)11 {12 if(n & 1)13 {14 ans = (ans * t) % 10;15 }16 t = t * t % 10;17 n >>= 1;18 }19 return ans;20 }21 int main()22 {23 __int64 n, m;24 scanf("%d", &n);25 for(int i = 0; i < n; i++)26 {27 scanf("%d", &m);28 printf("%d\n", pow1(m, m) % 10);29 }30 }