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次方后的前三位与后三位。并且后三位要求控制格式。
思路:这道题后三位可以用快速幂求出来,前三位就要用到log了。先说一下怎么求n^k的前三位。
我先设10^p=n^k,同时取log10,那么p=k*log10(n)。再设x=(int)p(整数部分),y=p-x(小数部分),那么10^p=10^x*10^y;由于10^x是10的倍数,那么10^y=n^k/10^x,就是n^k的值,不过就是小数点位置不同。那么只要求得y就能知道前三位的值了。
计算方法:
double p=k*log10(n);
p=p-(int)p;
int ans=(int)(pow(10,p)*100);
这就是前三位。
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,k;
int quickpow(int n,int k)
{
int ans=1,base=n%1000;
while(k)
{
if(k%2==1)
{
ans=(ans*base)%1000;
}
base=(base*base)%1000;
k/=2;
}
return ans;
}
int main()
{
int t,tt=1;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&k);
double a=(double)k*log10(n*1.0);
a-=(int)a;
double aa=pow(10.0,a);
int cc=quickpow(n,k);
printf("Case %d: %d %03d\n",tt++,(int)(aa*100),cc);
}
}