(HDU)1061 --Rightmost Digit( 最右邊的數字)

來源:互聯網
上載者:User

標籤: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( 最右邊的數字)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.