uva 11029 Leading and Trailing

来源:互联网 发布:淘宝女装美工 编辑:程序博客网 时间:2024/06/05 08:22

原题:
Apart from the novice programmers, all others know that you can’t exactly represent numbers raised to some high power. For example, the C function pow(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 and k 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 of n^k and TTT represents the last three digits of n^k. You are assured that n^k will contain at least 6 digits.

Sample Input
2
123456 1
123456 2

Sample Output
123…456
152…936

中文:
让你计算n^k的前3位和最后3位。

#include<bits/stdc++.h>using namespace std;typedef long long ll;const int mod=1000;ll quick_power(ll n, ll k){    ll res = 1;    while (k)    {        if (k & 1)            res = res * n % mod;        n = n * n % mod;        k >>= 1;    }    return res;}int main(){//  ios::sync_with_stdio(false);    int t;    scanf("%d",&t);    ll n,k;    while(t--)    {        scanf("%lld %lld",&n,&k);        ll b=quick_power(n,k);        ll a=(ll)(pow(10.0, 2 + fmod(k*log10(1.0*n),1)));        printf("%lld...%03lld\n",a,b);    }    return 0;}

思路

最后三位很好办,快速幂取模就行了。
前面三位怎么求?
网上搜了一下,感觉很神奇。
设n^k=p

对p取以10为底的对数得到的结果为q

q的整数位用x表示,小数位用y表示
关键就在这个小数位上面

反算回去
p=(10^x)×(10^y)

10^x表示的是p这个数是一个几位数,那么10^y就一定是p这个数缩小了x位

例如
假设p=654321
求出log10(p)的整数部分和小数部分x和y
x=5

654321 = (10^5)×(10^y)
明显(10^y)=6.54321
把(10^y)乘以100之后再取整就是前三位了,很奇妙哈-_-

自己手动写丢失精度,用到了库函数fmod