您的位置:首页 > 大数据 > 人工智能

Leading and Trailing LightOJ - 1282(快速幂)

2017-11-12 21:38 495 查看
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


题意:快速幂和fmod(C 库函数 double fmod(double x, double y) 返回 x 除以 y 的余数。) 快速幂的思想(假设我们要求a^b,那么其实b是可以拆成二进制的,该二进制数第i位的权为2^(i-1),例如当b==11时        a11=a(2^0+2^1+2^3)

  11的二进制是1011,11 = 2³×1 + 2²×0 + 2¹×1 + 2º×1,因此,我们将a¹¹转化为算 a2^0*a2^1*a2^3,也就是a1*a2*a8 ,看出来快的多了吧原来算11次,现在算三次, :&和>>

&运算通常用于二进制取位操作,例如一个数 & 1 的结果就是取二进制的最末位。还可以判断奇偶x&1==0为偶,x&1==1为奇。

运算比较单纯,二进制去掉最后一位

快速幂模板



#include<stdio.h>
#include<math.h>
#define long long mod 1000
long long qpow(long long base,long long n)
{
base%=mod;
long long ans=1LL;///如果和int型做运算就转化成int型,相当于longlong ans = 0;
while(n>0)
{
if(n&1)///奇数
ans=(ans*base)%mod;
base=(base*base)%mod;///偶数
n>>=1;
}
ans=ans%mod;
return ans;
}
int main()
{
int t;
scanf("%d",&t);
t=0;
long long n,k;
while(~scanf("%lld%lld",&n,&k))
{
t++;
double x=pow(10.0,fmod(k*log10(1.0*n),1));
x=x*100.0;
printf("Case %d: %d %03lld\n",t,(int)x,qpow(n,k));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: