UVa 11029 Leading and Trailing

來源:互聯網
上載者:User

UVa 11029 Leading and Trailing (如何計算n^k的開頭三位和末尾三位?)

11029 - Leading and Trailing

Time limit: 3.000 seconds

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=115&page=show_problem&problem=1970

Apart from the novice programmers, all others know that you can’t exactly represent numbers raised to some high power. For example, the C functionpow(125456, 455) can be represented in double data type format, but you won’t get all the digits of the result. However we can get at least some satisfaction if we could know few of the leading and trailing digits. This is the requirement of this problem.

Input

The first line of input will be an integer T<1001, where T represents the number of test cases. Each of the next T lines contains two positive integers,n and k. n will fit in 32 bit integer andk will be less than 10000001.

Output

For each line of input there will be one line of output. It will be of the format LLL…TTT, where LLL represents the first three digits ofn^k and TTT represents the last three digits of n^k. You are assured thatn^k will contain at least 6 digits.

Sample Input Output for Sample Input
2
123456 1
123456 2
123...456
152...936

思路:後三位好求,mod=1000的快速冪就是。

那前三位怎麼求呢?——對數

令x=lg(n^k)的整數部分,y=lg(n^k)的小數部分,則n^k由y決定——因為10^x是1000...0。所以10^y再乘上100取整就是前三位。

完整代碼:

/*0.015s*/     #include<cstdio>  #include<cmath>  #define sf scanf  #define pf printf  typedef long long ll;  const int mod = 1000;       ll pow_mod(int n, int k)  {      if (k == 0) return 1;      ll temp = pow_mod(n, k >> 1);      temp = temp * temp % mod;      if (k & 1) temp = temp * n % mod;///注意這裡中間運算結果會超int      return temp;  }       int main()  {      int t, n, k;      double intpart;      sf("%d", &t);      while (t--)      {          sf("%d%d", &n, &k);          pf("%d...%03lld\n", (int)pow(10.0, 2.0 + modf((double)k * log10(n), &intpart)), pow_mod(n, k));      }      return 0;  }

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.