UVA 11029 Leading and Trailing(大数n^k的前x位高精度问题)(好题)

13 篇文章 0 订阅


Download as PDF


Problem C

Leading and Trailing

Time limit: 2 seconds

 

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

Output for Sample Input

2

123456 1

123456 2

123...456

152...936

 

ProblemSetter: Shamim Hafiz

Alternate Solution: Jane Alam Jan



题意:求n^k的前三位数和末尾的三位数

思路:末尾的三位数直接快速幂+取模即可

因为末尾的三位数只由运算过程中末尾的三位数决定

而首三位数可以感性认知只由运算过程中前n位数决定,后面的数的精确度几乎对答案不影响,这种性质在计算机的浮点数中很好的实现了出来,所以试图把原问题用浮点运算解决。

n^k=10^(k*log10n)m,对10取对数就是为了把答案的信息全直观存在浮点数中,因为k*log10(n)的整数部分对答案没影响(只是*10000....),所以10^k*log10(n)的前三位就是答案。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;

const int mod = 1000;
typedef long long ll;
ll n,k;
int fans,bans;
int quickpow(ll x,int k)
{
    ll ans=1;
    while(k)
    {
        if(k&1) ans=(ans*x)%mod;
        x=x*x%mod;
        k>>=1;
    }
    return (int)ans;
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld%lld",&n,&k);
        bans=quickpow(n,k);
        double t=k*log10(n);
        t=t-(int)t;
        double a=pow(10,t);
        fans=(int)(a*100);
        printf("%d...%03d\n",fans,bans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值