<hdu - 1600 - 1601> Leftmost Digit && Rightmost Digit 數學方法求取大位元單位元字

來源:互聯網
上載者:User

標籤:scan   強制轉換   return   mos   color   block   lin   strong   target   

1060 - Leftmost Digit

1601 - Rightmost Digit

 

  1060題意很簡單,求n的n次方的值的最高位元,我們首先設一個數為a,則可以建立一個等式為n^n = a * 10^x;其中x也是未知的;

兩邊取log10有:lg(n^n) = lg(a * 10^x);

即:n * lg(n)  - x = lg(a);

現在就剩x一個變數了,我們知道x是值n^n的位元-1,a向下取整就是我們要求的數;

所以 按著上面的推導式翻譯成代碼就可以了(注意:數值的範圍和之間的強制轉換):

 1 /* 2  *   > File Name: 1060.cpp 3  *   > Author: Ddlm2wxm 4  *   > Mail: [email protected]  5  *   > Created Time: Wed 23 Nov 2016 09:36:14 PM CST 6   ***************************************************************/ 7  8 #include<iostream> 9 #include<cmath>10 #include <cstdio>11 using namespace std;12 13 typedef long long ll;14 typedef long double ld;15 16 int main() {17     int n;18     ll num, ans;19     ld t;20     scanf("%d", &n);21     while (n--) {22         scanf("%lld", &num);23         t = num * log10(num);24         ans = pow (10,  (t - (ll)t));25         printf("%lld\n", ans);26     }27     return 0;28 }
1060

 

  1061和1060題意一樣,只不過這道題是要求最低位上即個位上的數.在之間迴圈的時候有一些技巧:

①如果是偶數的話,直接第一次迴圈n * n % 10,然後更換n的值為n * n % 10;這樣下一次乘的時候就是兩個n和兩個n來相乘了,所以我們需要另外找一個變數來進行n的減半操作;迴圈到底即可。

②如果是奇數的話,在進行減半操作之後,就會變成(n - 1) / 2的數,自然就會少一次n,所以我們需要當n為奇數時候使用res記錄一下n的值。迴圈到底即可。

閑話不多話,上代碼:

 1 /* 2  *   > File Name: 1061.cpp 3  *   > Author: Ddlm2wxm 4  *   > Mail: [email protected]  5  *   > Created Time: Wed 23 Nov 2016 09:40:03 PM CST 6   *****************************************************************/ 7  8 #include <iostream> 9 #include <algorithm>10 #include <string>11 #include <cstring>12 #include <cstdio>13 using namespace std;14 15 int mod_exp (int n) {16     int res = 1, t = n % 10, b = n;17     while (b) {18         if (b & 1) {19             res *= t;20             res %= 10;21         }22         t *= t;23         t %= 10;24         b >>= 1;25     }26     return res;27 }28 29 int main() {30     int T, n;31     scanf ("%d", &T);32     while (T--) {33         scanf ("%d", &n);34         cout << mod_exp (n) << endl;35     }36     return 0;37 }
1061

 

 歡迎碼友一起評論更簡單的方法,一起成長。

<hdu - 1600 - 1601> Leftmost Digit && 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.