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的前三位和后三位。
题解:题目意思就是让求 n 的 k 次方的高三位和低三位(输出至少是六位)。 低三位就是快速幂求模啦,高三位就是数学公式的变换
如x = 123456,我们转换一下:x = 1.23456 * 10^5,即log(x) = 5 + y;
有了这个式子我们就可以知道,10^y一定等于1.23456,不信你可以去试试。然后前三位就是10^y*100咯。
前4位,前5位...n位其实都类似,关键是掌握题目的方法。
还有一个要注意,可能最后3位mod1000的时候可能为0,所以输出需要%03lld
写了这道题也算是了解了一下 < cmath > 里面 fmod 函数 和 floor 函数的用法了
使用fmod(a, 1)表示求浮点型数 a 的小数部分。
原型:extern float fmod(float x, float y)
用法:#include <math.h>
功能:计算 x / y 的余数
说明:返回值为双精度型,符号同 x ;如:fmod ( f , (int)f )即可得到小数点后的部分
代码:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
LL qpow(LL a,LL b)
{
LL base=a,ans=1;
while(b)
{
if(b&1)
{
ans=(ans*base)%1000;
}
base=(base*base)%1000;
b>>=1;
}
return ans%1000;
}
int main()
{
int t,text=0;
scanf("%d",&t);
while(t--)
{
LL n,k;
scanf("%lld %lld",&n,&k);
// 下面的f其实就是题解所说的5+y,y就是小数部分。
double f=k*log10(n*1.0); // 以下是两种不同的取小数位的方法,和两种输出方式
//LL start=(LL)pow(10.0,f-floor(f)+2.0);
LL start=(LL)pow(10.0,fmod(f,1.0)+2.0); // 取三位时加 2.0,那么同理取 n 位时加 n-1 就行了
//int start=(LL)pow(10.0,f-floor(f)+2.0);
//int end=qpow(n,k);
//printf("Case %d: %d %03d\n",++text,start,end);
printf("Case %d: %lld %03lld\n",++text,start,qpow(n,k));
}
return 0;
}