Light-oj-1282 Leading and Trailing(数学取位)

来源:互联网 发布:长戟大兜虫淘宝 编辑:程序博客网 时间:2024/06/11 03:04

Leading and Trailing

Description

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的前3位和后三位;

求最后的三位,可以通过直接取余(快速幂)得到;求前三位则需要一些数学知识对于给定的一个数n,它可以写成10^a,其中这个a为浮点数,则n^k=(10^a)^k=10^a*k=(10^x)*(10^y);其中x,y分别是a*k的整数部分和小数部分,对于t=n^k这个数,它的位数由(10^x)决定,它的位数上的值则有(10^y)决定,因此我们要求t的前三位,只需要将10^y求出,在乘以100,就得到了它的前三位。

n^k=a.bc*10^m ( m为n^k的位数,即m=(int)lg(n^k)=(int)(k*lgn) );

            求对数:  k*lgn=lg(a.bc)+m

             即 a.bc=10^(k*lgn-m)=10^(k*lgn-(int)(k*lgn));

              abc=a.bc*100;



#include<cstdio>#include<math.h>typedef long long ll;ll n,k;ll qpow(ll n,ll k){    ll res=1;    while(k>0){        if(k%2==1)    res=(res%1000)*(n%1000)%1000;        n=(n%1000)*(n%1000)%1000;        k=k/2;    }    return res%1000;}ll f(ll n){    double x=k*log10(n)-(int)(k*log10(n));    return pow(10,x)*100;}int main(){    int T;    scanf("%d",&T);    int tag=1;    while(T--){        scanf("%lld%lld",&n,&k);        printf("Case %d: %lld %03lld\n",tag++,f(n),qpow(n,k));    }    return 0;}



0 0