UVA Leading and Trailing 11029【数学+快速幂】

本文介绍了一种高效算法,用于快速幂运算并获取结果的前三位和最后三位数字。通过数学原理和代码实现,展示了如何在有限时间内解决实际问题。

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

11029 - Leading and Trailing

Time limit: 3.000 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
2
123456 1
123456 2
Sample Output
123...456
152...936


题意:给你一个数n,让你求它的k次方之后的前三位和最后三位。

解题思路:

后三位比较好想,直接快速幂取余就可以了。主要最前面三位的计算。

我们可以想一个数,例如1589.  如果这个数换算一下,换成10^x次方。那么x就等于log10(1589).  而如果我们把log10(1589)Mod 1,对1取余的结果是我们只取x的小数位。试想,如果把x分成整数z和小数g,那么10^x=10^(z+g)=10^g*10^z,z是整数,所以10^z是10000~,一个数乘以10^z就代表我们要的数是z+1位的数字。如果把z换成2.我们就得到了一个三位的数字,而且这个数字就是n^k的前三位。

*fmod函数。fmod( x , y ),计算x / y的余数。

AC代码:

#include <stdio.h>
#include <math.h>
#include <vector>
#include <queue>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>

using namespace std;

typedef long long LL;

LL pow_mod(LL x,LL n)
{
    LL res=1;
    while(n){
        if(n&1) res=res*x%1000;
        x=x*x%1000;
        n>>=1;
    }
    return res;
}

int main()
{
    int t;
    scanf("%d",&t);
    int xp=0;
    while(t--){
        LL n,k;
        scanf("%lld%lld",&n,&k);
        int ans=pow(10,2+fmod(k*log10(n),1));
        int res=pow_mod(n,k);
        printf("%d...%03d\n",ans,res);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值