Problem C | Leading and Trailing |
Time limit: 2 seconds |
Apart from the novice programmers, all others know that you can’t exactly represent numbers raised to some high power. For example, the C function pow(125456, 455) can be represented in double data type format, but you won’t get all the digits of the result. However we can get at least some satisfaction if we could know few of the leading and trailing digits. This is the requirement of this problem.
Input
The first line of input will be an integer T<1001, where T represents the number of test cases. Each of the next T lines contains two positive integers, n and k. n will fit in 32 bit integer and k will be less than 10000001.
Output
For each line of input there will be one line of output. It will be of the format LLL…TTT, where LLL represents the first three digits of n^k and TTT represents the last three digits of n^k. You are assured that n^k will contain at least 6 digits.
Sample Input | Output for Sample Input |
2 123456 1 123456 2 | 123...456 152...936 |
ProblemSetter: Shamim Hafiz
Alternate Solution: Jane Alam Jan
题意:求n^k的前三位数和末尾的三位数
思路:末尾的三位数直接快速幂+取模即可
因为末尾的三位数只由运算过程中末尾的三位数决定
而首三位数可以感性认知只由运算过程中前n位数决定,后面的数的精确度几乎对答案不影响,这种性质在计算机的浮点数中很好的实现了出来,所以试图把原问题用浮点运算解决。
n^k=10^(k*log10n)m,对10取对数就是为了把答案的信息全直观存在浮点数中,因为k*log10(n)的整数部分对答案没影响(只是*10000....),所以10^k*log10(n)的前三位就是答案。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const int mod = 1000;
typedef long long ll;
ll n,k;
int fans,bans;
int quickpow(ll x,int k)
{
ll ans=1;
while(k)
{
if(k&1) ans=(ans*x)%mod;
x=x*x%mod;
k>>=1;
}
return (int)ans;
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%lld%lld",&n,&k);
bans=quickpow(n,k);
double t=k*log10(n);
t=t-(int)t;
double a=pow(10,t);
fans=(int)(a*100);
printf("%d...%03d\n",fans,bans);
}
return 0;
}