E - 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 nk.

Input

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 < 231) and k (1 ≤ k ≤ 107).

Output

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.

Sample Input

5

123456 1

123456 2

2 31

2 32

29 8751919

Sample Output

Case 1: 123 456

Case 2: 152 936

Case 3: 214 648

Case 4: 429 296

Case 5: 665 669

题意:我们目的要找出n^k的前三位和后三位,后三位注意补零。

题解:直接算肯定爆,后三位的思路很清晰,我们直接用快速幂对1000取mod即可。

前三位用到了对数转换:设n^k=A,则10^(k*lg(n))==A.   //对数性质要掌握牢固

k是整数,10的k次方后肯定是1000……的形式,那么我们只需考虑10^(lg(n)).

设lg(n)的整数部分为z,小数部分为d,则10^z的形式也为1000……的形式,只需考虑10^d即可。

算出来10^d以后再乘以100取整即可,或许直接计算10^(2+d).  写代码时用到了fmod的函数,其功能为返回小数部分。

函数原型:fmod(float x,float y) 返回x%y;

这里调用fmod(k*lg(n),(int)(k*lg(n)))返回即为小数部分。

#include<iostream>
#include<stdio.h>
#include<cmath>
#include<iomanip>
using namespace std;
typedef long long ll;
ll n,k;
int x,y;
ll quickpow(ll a,ll b,int mod)
{
    ll ans=1;
    while(b)
    {
        if(b&1)
            ans=(ans*a)%mod;  //乘法不会爆long long 
        a=(a*a)%mod;
        b>>=1;
    }
    return ans;
}
int main()
{
    int t;
    cin>>t;
    int q=1;
    while(t--)
    {
        cin>>n>>k;
        x=(int)pow(10,2+fmod(k*log10(n),(int)(k*log10(n))));
        y=quickpow(n,k,1000);  //运用快速幂得到后三为即可
        cout<<"Case "<<q++<<":"<<" ";   //注意输出格式,我去,因为这个W了好几次
        cout<<x<<" "<<setw(3)<<setfill('0')<<y<<endl;  //注意后三位补0
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值