uva 11029 Leading and Trailing

原题:
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值