標籤:
Problem DescriptionGiven a positive integer N, you should output the most right digit of N^N. InputThe 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). OutputFor each test case, you should output the rightmost digit of N^N. Sample Input234 Sample Output7 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. 最先想到的是一個一個算,但是由於資料範圍太大,O(n^2)的時間複雜度對於n = 10億時,10億^10億次乘法運算實在是不能忍受的。因此下面的程式逾時(Time Limit Exceeded)。
#include<stdio.h>int main(void){ int cases, n, copy_n, result; scanf("%d", &cases); while(cases--) { scanf("%d", &n); copy_n = n; n = n%10; result = 1; while(copy_n--) { result = (result*n)%10; } printf("%d\n", result); } return 0;}
下面,快速冪一來就AC了:
#include<stdio.h>int my_power(int m, int n); // 求m的n次方的尾數int main(void){ int cases, n; scanf("%d", &cases); while(cases--) { scanf("%d", &n); printf("%d\n", my_power(n, n)); } return 0;}int my_power(int m, int n){ m = m%10; if(n == 1) return m; if(n%2 == 0) return ( my_power(m*m, n/2) ) % 10; else return ( my_power(m*m, n/2)*m ) % 10;}
可以看到,快速冪的時間複雜度是O(logn),n = 10億時,大約32次遞迴調用就能出結果,效率極大的提高了。
HDU_1061:Rightmost Digit