11029 - Leading and Trailing
Time limit: 3.000 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
2
123456 1
123456 2
Sample Output
123...456
152...936
题意:给你一个数n,让你求它的k次方之后的前三位和最后三位。
解题思路:
后三位比较好想,直接快速幂取余就可以了。主要最前面三位的计算。
我们可以想一个数,例如1589. 如果这个数换算一下,换成10^x次方。那么x就等于log10(1589). 而如果我们把log10(1589)Mod 1,对1取余的结果是我们只取x的小数位。试想,如果把x分成整数z和小数g,那么10^x=10^(z+g)=10^g*10^z,z是整数,所以10^z是10000~,一个数乘以10^z就代表我们要的数是z+1位的数字。如果把z换成2.我们就得到了一个三位的数字,而且这个数字就是n^k的前三位。
*fmod函数。fmod( x , y ),计算x / y的余数。
AC代码:
#include <stdio.h> #include <math.h> #include <vector> #include <queue> #include <string> #include <string.h> #include <stdlib.h> #include <iostream> #include <algorithm> using namespace std; typedef long long LL; LL pow_mod(LL x,LL n) { LL res=1; while(n){ if(n&1) res=res*x%1000; x=x*x%1000; n>>=1; } return res; } int main() { int t; scanf("%d",&t); int xp=0; while(t--){ LL n,k; scanf("%lld%lld",&n,&k); int ans=pow(10,2+fmod(k*log10(n),1)); int res=pow_mod(n,k); printf("%d...%03d\n",ans,res); } return 0; }
版权声明:本文为博主原创文章,转载请注明出处。