LightOj 1282 Leading and Trailing ----数论

Time limit   2000 ms

Memory limit   32768 kB

OS   Linux

Source   Problem Setter: Shamim Hafiz

              Special Thanks: Jane Alam Jan (Solution, Dataset)

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的前三位和后三位。后三位相对于比较好求,只需要快速幂取模就可以了。前三位就要推导了:当k=1是,令

log10N=d推出N=10^d(d=a+i,其中a为整数部分,i为小数部分)则N=10^a*10^i。又N=123456=1.23456*10^5,又log10(123456)=5即a=5.则N=10^5*10^i(10^i=1.23456)所以前三位为10^i*100.

所以n^k的前三位=10^(k*log10N-(int)k*log10N)*100.

注意:输出是一定要注意题目要求至少包含六位数字,不足的补零。我就因为这个细节没有看到结果WA了超多次╮(╯▽╰)╭

#include <iostream>
#include <stdio.h>
#define ll long long
#include <math.h>
using namespace std;
int pows(ll a,ll b)
{
    if(b==0)return 1;
    if(b==1)return a%1000;
    ll ans=1;
    while(b)
    {
        if(b&1)ans=(ans*a)%1000;
        b>>=1;
        a=(a*a)%1000;
    }
    return ans;
}
int main()
{
    int t;
    ll n,k;
    cin>>t;
    int cont=0;
    while(t--)
    {
        cin>>n>>k;
        double x=k*log10(n);
        double y=pow(10,x-(int)x)*100;
        int yy=pows(n,k);
        printf("Case %d: %d %03d\n",++cont,(int)y,yy);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/sinat_41233888/article/details/81415530