LightOJ1282( Leading and Trailing )

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

分析:题目让求nk的前3位和最后3位,

后3位用快速幂就行了,注意后3位有可能出现前导0;

前3位求法:nk=a.bc*10^m,(0<a.bc<10)

那么k*log10(n) = log10(a.bc)+m;

其中m=(int)k*log10(n),令t=log10(a.bc)=k*log10(n)-(int)k*log10(n),

那么答案是pow(10.0,t)的前3位。

#include<cstdio>
#include<cmath>
long long Pow(long long N,int k)
{
    if(k==1) return N%1000;
    long long y=Pow(N,k/2);
    y=y*y;
    y=y%1000;
    if(k%2) y=y*N;
    return y%1000; 
}

int main()
{
    int T,k,cas=0;long long N;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld%d",&N,&k);
        long long last=Pow(N%1000,k);
        double a=k*log10((double)N)-(long long)(k*log10((double)N));
        a=pow(10.0,a);
        printf("Case %d: %d %03d
",++cas,(int)(a*100),last%1000);
    }
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/ACRykl/p/8576470.html