Leading and Trailing

题目:

You are given two integers: n and k, your task is to find the most significant three digits, and least significant three digits of n^{k}.

输入:

Input starts with an integer T (≤ 1000), denoting the number of test cases.

Each case starts with a line containing two integers: n (2 ≤ n < 2^{31}) and k (1 ≤ k ≤ 10^{7}).

输出:

For each case, print the case number and the three leading digits (most significant) and three trailing digits (least significant). You can assume that the input is given such that nk contains at least six digits.

样例输入:

5

123456 1

123456 2

2 31

2 32

29 8751919

样例输出:

Case 1: 123 456

Case 2: 152 936

Case 3: 214 648

Case 4: 429 296

Case 5: 665 669

这个题是要求输出n的k次幂的前三位数和最后三位数。最后三位数比较容易求,用快速幂求出数之后直接%1000就可以了,为什么是1000,因为对1000的余数正好是三位数。前三位数,借阅网上的方法:对于任意的一个数都可以转化成10^x(x 为浮点数) = 10^a * 10^b (a,b 也是浮点数)的形式, 其中 10 ^ a 表示结果的位数,10^b 表示对应位的值。所以可以先求到 x 的值,再求到 b 的值,求到 10^b ,即求到了该数对应位置的值(浮点数),再乘以系数,就能得到前3位的值;

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
ll quick(ll a,ll b)
{
    ll ans=1;
    a=a%1000;
    while(b!=0)
        {
            if(b&1)
                ans=(ans*a)%1000;
           b /=2;
            a=(a*a)%1000;
        }
        return ans;
}
int main()
{
    int t;
    scanf("%d",&t);
    int cas=1;
    while(t--)
    {
        ll n,k;
        scanf("%lld%lld",&n,&k);
        ll res1,res2;
        res2= quick(n,k)%1000;
        double num = k*log10(n*1.0);//n的k次方等于10的num次方,所以转换一下就是这个式子
        num -= ll(num);//得到上面说的小数部分
        res1=ll(pow(10,num) * 100);
        printf("Case %d: %lld %03lld\n", cas++, res1, res2);
    }
    return 0;
}

 

猜你喜欢

转载自blog.csdn.net/zhangjinlei321/article/details/81672313