UVA11029 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 . . . T T T, where LLL represents the first three digits of n^k and T T T 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

问题链接UVA11029 Leading and Trailing
问题简述:(略)
问题分析
    计算n^k的前3位和后3位。
    后3位用快速模幂来计算。
    前3位则根据数学公式,按浮点数进行计算。假设n^K= X 10 ^(len-1) ,其中X是规范化表示的小数点前唯一的1位10进制数字,len是10进制数的长度,那么两边取对数后得Klog10(n)=(len-1)+log10(X);令T=Klog10(n),那么根据取对数后的等式,去除整数部分,tmp的小数部分=log(X),故T=10^X,即X=pow(10,T)。而T值用程序语言的表达式来表示的话,T=Klog10(n)-(long long)K*log10(n),整数用long long类型。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++程序如下:

/* UVA11029 Leading and Trailing */

#include <bits/stdc++.h>

using namespace std;

typedef long long LL;
const int MOD = 1000;

// 快速模幂
LL powmod(LL x, LL n, LL m)
{
    LL result = 1;
    for(; n; n >>= 1) {
        if(n & 1) {
            result *= x;
            result %= m;
        }
        x *= x;
        x %= m;
    }

    return result;
}

int main()
{
    int t;
    LL n, k, ans1, ans2;
    scanf("%d",&t);
    while(t--) {
        scanf("%lld%lld", &n, &k);

        ans2 = powmod(n, k, MOD);
        double tmp = k * log10(n);
        tmp=pow(10.0, tmp - (long long)tmp);
        ans1 = (LL)(tmp * 100);

        printf("%lld...%03lld\n", ans1, ans2);
    }

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/tigerisland45/p/10469421.html