1282 - Leading and Trailing 求n^k的前三位和后三位。

时间:2023-03-10 00:09:57
1282 - Leading and Trailing   求n^k的前三位和后三位。
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 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.

分析:后三位直接快速幂取余得,对于体格给定的整数n可以写成n = 10^a形式,其中a是浮点数, n ^ k = (10 ^ a) ^ k = (10 ^ x) * (10 ^ y), 其中x,y分别为ak的整数部分和小数部分,对于t=n^k这个数,他的位数由10^x决定,他的位数上的值由10^y决定。因此我们要求t的前三位,只用求出10^y就可以了。

fmod() 用来对浮点数进行取模(求余),其原型为:
    double fmod (double x);

设返回值为 ret,那么 x = n * y + ret,其中 n 是整数,ret 和 x 有相同的符号,而且 ret 的绝对值小于 y 的绝对值。如果 x = 0,那么 ret = NaN。

fmod 函数计算 x 除以 y 的 f 浮点余数,这样 x = i*y + f,其中 i 是整数,f 和 x 有相同的符号,而且 f 的绝对值小于 y 的绝对值。

代码:

#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>

using namespace std;
typedef long long ll;
const int maxn = 1e7+5;
const int mod = 1000;

int quickmi(int a, int b)
{
if(b == 0)
return 1;

int tmp = quickmi(a, b>>1);

tmp = tmp * tmp % mod;

if(b & 1)
tmp = tmp * (a % mod) % mod;

return tmp % mod;

}
int main(void)
{
int T, cas;
int n, m;

scanf("%d", &T);

cas = 0;

while(T--)
{

cas++;

scanf("%d%d", &n, &m);

int last = quickmi(n % 1000, m);

double y = 2.0 + fmod(m * log10(n * 1.0), 1);
int first = pow(10.0, y);

printf("Case %d: %03d %03d\n", cas, first, last);

}

return 0;
}