標籤:namespace 保留 資料 分享 i++ splay while std open
題目連結:http://vjudge.net/problem/HDU-1061
這個題目要求出N個N相乘的個位,直接求結果肯定資料溢出。
其實只要每次得出一個數字保留個位和N相乘就可以了,
因為A*B=C,對於個位而言,A(個位)*B(個位)=C(個位)始終成立。
1<=N<=1,000,000,000,這樣寫還是TLE了。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 6 int main() 7 { 8 int t,n,i; 9 scanf("%d",&t);10 while(t--)11 {12 scanf("%d",&n);13 int ans=1;14 for(i=1;i<=n;i++)15 {16 ans*=n;17 ans%=10;18 }19 printf("%d\n",ans);20 }21 return 0;22 }View Code
來換一個思路,沿用上面的思路,我們來找一個個位周期:
0:0 0 0 0 0 0 0 0 0 0
1:1 1 1 1 1 1 1 1 1 1
2:2 4 8 6 2 4 8 6 2 4
3:3 9 7 1 3 9 7 1 3 9
4:4 6 4 6 4 6 4 6 4 6
5:5 5 5 5 5 5 5 5 5 5
6:6 6 6 6 6 6 6 6 6 6
7:7 9 3 1 7 9 3 1 7 9
8:8 4 2 6 8 4 2 6 8 4
9:9 1 9 1 9 1 9 1 9 1
有一個普遍規律,周期為4。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 6 int main() 7 { 8 int t,n,temp,ans[4]; 9 scanf("%d",&t);10 while(t--)11 {12 scanf("%d",&n);13 temp=n;14 temp%=10;15 ans[1]=temp;16 ans[2]=(ans[1]*temp)%10;17 ans[3]=(ans[2]*temp)%10;18 ans[0]=(ans[3]*temp)%10;19 printf("%d\n",ans[n%=4]);20 }21 return 0;22 }View Code
(HDU)1061 --Rightmost Digit( 最右邊的數字)