UVA-11029-Leading and Trailing-(快速幂,log10函数求大数首末数)

本文介绍了一种计算n^k的前三位和后三位数字的方法,并提供了一个使用C++实现的具体示例。该算法利用了对数运算来获取前三位数字,并通过模运算得到后三位数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=115&page=show_problem&problem=1970

part 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 kn 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



求n^k的前3位和后3位

n^k = X *10 ^(len-1) //len是整数的长度,X是10整数位置只有一位的n^k值的浮点数表示
两边取对数:

K*log10(N)=(len-1)+log10( X )

double tmp=k*log10(n*1.0); //temp等于左边

tmp=tmp-(long long)tmp;//因为log(x)小于1,而(len-1)为整数,所以temp减去整数部分就只剩下log10(x)

tmp=pow(10.0,tmp); //10^[log10(x)]==x

ans1=(ll)(tmp*100); //x*100整数部分为3位

代码:

#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<queue>
#include<cstring>
#include<map>
using namespace std;
#define M 1000005
typedef long long ll;

int n;
ll powmod(ll n,ll k)//快速幂
{
    ll res=1;
    while(k>0)
    {
        if(k&1)
            res=res*n%1000;
        n=n*n%1000;
        k>>=1;
    }
    return res;
}

int main()
{
    int T;
    ll n,k,ans1,ans2;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld%lld",&n,&k);
        ans2=powmod(n,k);
        double tmp=k*log10(n*1.0);
        tmp=tmp-(long long)tmp;
        tmp=pow(10.0,tmp);
        ans1=(ll)(tmp*100);
        printf("%lld...%03lld\n",ans1,ans2);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值