LightOJ 1282 Leading and Trailing

LightOJ 1282 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 n^k .

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 < 2 31 ) n (2 ≤ n < 2^{31}) and k ( 1 k 1 0 7 ) k (1 ≤ k ≤ 10^7) .

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

后三位很简单,用快速幂模1000即可~(注意输出格式,因为取模后可能不满三位)
下面考虑前三位,我们可以进行如下转化:
n k n^k = 1 0 l o g 10 n k 10^{log_{10}n^k} = 1 0 k l o g 10 n 10^{k*log_{10}n}
然后我们令
a + b = k l o g 10 n a+b=k*log_{10}n a a 为整数部分, b b 为小数部分
所以: 1 0 k l o g 10 n 10^{k*log_{10}n} = 1 0 a + b 10^{a+b} = 1 0 a 1 0 b 10^a*10^b
不难发现 1 0 a 10^a 不影响答案,而 1 0 b 10^b 取整范围为(0,10),所以我们将其乘100就得到了前三位的值~
关键点就落在了求 b b 的值上,恰好有一个函数 f m o d fmod 是求一个数的小数部分,AC代码如下:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod=1000;
ll power(ll a,ll b){return b?power(a*a%mod,b/2)*(b%2?a:1)%mod:1;}
ll f(ll n,ll k){
    double x;
    return pow(10,modf((double)(k*log10(n)),&x))*100;
}
int main()
{
    ll n,k,t;
    scanf("%lld",&t);
    for(ll i=1;i<=t;i++){
        scanf("%lld%lld",&n,&k);
        printf("Case %lld: %lld %03lld\n",i,f(n,k),power(n,k));
    }
    return 0;
}
发布了479 篇原创文章 · 获赞 38 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/qq_43765333/article/details/105726769