Time Limit: 2 second(s) | Memory Limit: 32 MB |
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 | Output for Sample Input |
5 123456 1 123456 2 2 31 2 32 29 8751919 | Case 1: 123 456 Case 2: 152 936 Case 3: 214 648 Case 4: 429 296 Case 5: 665 669 |
SPECIAL THANKS: JANE ALAM JAN (SOLUTION, DATASET)
题目大意:给你一个n,一个k,问n的k次幂这个数的前三位是啥后三位是啥,保证n的k次幂为6位数。
解题思路:后三位好求,每次都取结果的后三位乘积就行了,不过这里普通方法超时,用快速幂求后三位;求前三位,假设n^k=num,那么同取以十为底的对数,那么两边变成log10(n^k)=log10(num),把k提前,那么得到k*log10(n)=log10(num),num=10^(k*log10(n)),所以这里先求出来k*log10(n),令他等于tmp,之中tmp=a+b,a是整数,b是小数,10^(a+b),a控制小数点的位置,而b才是关键,剔除那个整数部分a,由于b是小数,那么10的b次幂是一个大于1于10的数,那么乘以100就得到了前三位了。
代码如下:
#include <cstdio>
#include <cmath>
#include <cstring>
long long quickpow(long long a,long long b)//快速幂求后三位
{
a=a%1000;
long long res=1;
while(b)
{
if(b&1)
{
res=res*a%1000;
}
a=a*a%1000;
b=b/2;
}
return res;
}
int main()
{
int t;
scanf("%d",&t);
long long n,k;
long long kcase=1;
while(t--)
{
scanf("%lld%lld",&n,&k);
double tmp1=(log10(n))*(double)k;//先计算这个式子
tmp1=tmp1-(long long)tmp1;//剔除整数部分
double tmp=pow(10,tmp1);//计算10的tmp1次幂 ,得到一个大于1小于十的数
long long qian=(long long)(tmp*100);//向后移动两位
long long hou=quickpow(n,k);//快速幂求
printf("Case %lld: %lld ",kcase++,qian);
if(hou<10)
{
printf("00%lld\n",hou);//记得补0
}
else
{
if(hou<100)
{
printf("0%lld\n",hou);//记得补0
}
else
{
printf("%lld\n",hou);
}
}
}
return 0;
}