lightoj-1282-Leading and Trailing【快速幂】(两个数学函数的使用)

来源:互联网 发布:网络销售适合什么人做 编辑:程序博客网 时间:2024/05/31 15:18

题目链接:点击打开链接

1282 - Leading and Trailing
   PDF (English)StatisticsForum
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 containsat 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

 


PROBLEM SETTER: SHAMIM HAFIZ
SPECIAL THANKS: JANE ALAM JAN (SOLUTION, DATASET)

题解:题目意思就是让求 n 的 k 次方的高三位和低三位(输出至少是六位)。    低三位就是快速幂求模啦,高三位就是数学公式的变换

如x = 123456,我们转换一下:x = 1.23456 * 10^5,即log(x) = 5 + y;

有了这个式子我们就可以知道,10^y一定等于1.23456,不信你可以去试试。然后前三位就是10^y*100咯。

前4位,前5位...n位其实都类似,关键是掌握题目的方法。

还有一个要注意,可能最后3位mod1000的时候可能为0,所以输出需要%03lld

写了这道题也算是了解了一下 < cmath > 里面 fmod 函数 和 floor 函数的用法了

使用fmod(a, 1)表示求浮点型数 a 的小数部分。

 原型:extern float fmod(float x, float y)
 用法:#include <math.h>
 功能:计算 x / y 的余数
 说明:返回值为双精度型,符号同 x ;如:fmod ( f , (int)f )即可得到小数点后的部分

#include<cstdio>#include<cstring>#include<cmath>#include<algorithm>using namespace std;typedef long long LL;LL qpow(LL a,LL b){LL base=a,ans=1;while(b){if(b&1){ans=(ans*base)%1000;}base=(base*base)%1000;b>>=1;}return ans%1000;}int main(){int t,text=0;scanf("%d",&t);while(t--){LL n,k;scanf("%lld %lld",&n,&k);double f=k*log10(n*1.0); // 以下是两种不同的取小数位的方法,和两种输出方式 //LL start=(LL)pow(10.0,f-floor(f)+2.0);LL start=(LL)pow(10.0,fmod(f,1.0)+2.0); // 取三位时加 2.0,那么同理取 n 位时加 n-1 就行了//int start=(LL)pow(10.0,f-floor(f)+2.0);//int end=qpow(n,k);//printf("Case %d: %d %03d\n",++text,start,end);printf("Case %d: %lld %03lld\n",++text,start,qpow(n,k));}return 0;}

0 0
原创粉丝点击