Leading and Trailing(巧妙利用log解决次方问题)
2017-07-26 18:29
387 查看
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); } }
相关文章推荐
- lightoj 1282 - Leading and Trailing (数学--log使用)
- UVA 11029 Leading and Trailing(大数n^k的前x位高精度问题)(好题)
- 【Light-oj】-1282 - Leading and Trailing(数论,快速幂,log,好)
- 利用矩阵的迹巧妙解决矩阵的求导问题
- uvaoj 11029 Leading and Trailing 取log和快速幂
- Uva 11029 – Leading and Trailing(快速幂取模,log(x)的应用)
- 第十周项目3 利用二叉树遍历思想解决问题(5)
- 利用优先级队列解决k路归并问题
- 12.利用3种方式来解决浮动脱标的问题
- 试着用React写项目-利用react-router解决跳转路由等问题(二)
- LightOJ 1282 Leading and Trailing (快速幂+fmod)
- 巧妙解决windows下 copy命令不接受太长路径的问题
- 第十周项目3-利用二叉树遍历思想解决问题
- 第十周 项目3-利用二叉树遍历思想解决问题
- 利用Spring的AbstractRoutingDataSource解决多数据源的问题
- E - Leading and Trailing 求n^k得前三位数字以及后三位数字,保证一定至少存在六位。
- 利用ajaxSubmit提交的时候,解决多个input name相同的问题
- 解决ajax不能访问本地文件问题(利用js跨域原理)
- 利用List的Sort()、Find()、FindAll()、Exist()来解决一些问题
- 利用Shell 脚本解决DDOS攻击问题