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,求nk的前三位数和后三位数。
核心思想:
后三位:
mod1000的快速幂。
前三位:
设x=log10(nk)=k*log10(n),则nk=10x,
记x的整数部分为a,小数部分为b(即x=a+b),则nk=10a·10b。
10a决定小数点的位置,10b决定数字大小。
因为0≤b<1,所以1≤10b<10。(即10b的小数点前一定是一位非零数1~9)
那么,10b+2的小数点前一定是一个三位数,舍掉其小数部分取整就是答案。
另外:
获取一个浮点数的小数部分用math头文件下的函数fmod。
函数原形:double fmod(double x,double y),返回值是x除以y的余数,符号和x相同。
fmod(x,1.0)就可以获得x的小数部分。
获取一个浮点数的整数部分用强制类型转换。
double x;
ll a=ll(x);//也可以写成 ll a=x;
在不超过long long范围的前提下,就可以获得x的整数部分(不会四舍五入,而是直接舍掉小数)。
参考博客:https://blog.youkuaiyun.com/oenheng/article/details/52294559
代码如下:
#include<cstdio>
#include<iostream>
#include<cmath>
using namespace std;
typedef long long ll;
const ll mo=1000;
ll ksm(ll n,ll b)
{
ll ans=1;
ll t=n;
while(b)
{
if(b&1)ans=(ans*t)%mo;
t=(t*t)%mo;
b>>=1;
}
return ans;
}
int main()
{
int T,ca=0;
cin>>T;
while(T--)
{
ll n,k;
scanf("%lld%lld",&n,&k);
double x=k*log10(n*1.0);
double b=fmod(x,1.0);
b=pow(10.0,b+2.0);
ll z=b;
printf("Case %d: %lld %03lld\n",++ca,z,ksm(n,k));
}
return 0;
}