UVA Leading and Trailing 11029【数学+快速幂】
2015-08-18 14:19
369 查看
11029 - Leading and Trailing
Time limit: 3.000 secondsApart 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; }
相关文章推荐
- socket failed:EACCES(Permission denied)
- grails使用select标签输出多个内容
- 【转载】Neural Networks for Digit Recognition with Pybrain
- Open drain & push pull 原理
- sgu-300.Train
- POJ 2585 Window Pains【拓扑】
- 注解(annotaion)一对一、一对多、多对一
- LightOJ 1038-Race to 1 Again(概率dp)
- Contains Duplicate II
- Contains Duplicate
- Run-Time Check Failure #2 - Stack around the variable 'cmd' was corrupted 的可能原因
- org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role
- 【优先队列】POJ2010- Moo University-Financial Aid
- 2015 HUAS Summer Trainning #6~L
- hdu 5380 Travel with candy 单调队列 2015 Multi-University Training Contest 8
- wait_event_interruptible 使用方法
- [LeetCode] Contains Duplicate II
- 如何使用KeyChain保存和获取UDID
- IE8下MSPAINT保存的PNG显示不正常
- Aicrack-ng破解WPA/WPA2