You are given two integers: n and k, your task is to find the most significant three digits, and least significant three digits of n.k.
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 < 2.31) and k (1 ≤ k ≤ 10.7).
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 n.k 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次方的前三位和末三位数字。
由于给的数据过大,如果直接求n的k次方,得出的结果绝对会溢出。
如果一个一个相乘再取余,复杂度过高,会超时,所以就需要用到快速幂。
快速幂
int power(int a,int n) { int s=1; while(n) { if(n&1) s*=a; a*=a; n>>=1; } return s; }
在数据较大时,用如下算法可求取a的n次方的前b位。
int power(int a,int n,int b) { double s=n*log10(a); int ss=s; cout<<(int)(pow(10,s-ss)*pow(10,b)); }
本题答案
#include<bits/stdc++.h> using namespace std; int k=1; long long tp(long long m,long long n) { long long s=1; while(n)//Èç¹ûÒ»¸öÒ»¸öÏà³ËÔÙÈ¡ÓิÔӶȹý¸ß»á³¬Ê±£» { if(n&1)//ÅжÏÆæżÐÔ£» s=s*m%1000; m=m*m%1000; n>>=1;//µÈͬÓÚn/=2; } return s; } int main() { long long x,y,p; cin>>p; while(p--) { cin>>x>>y; double ss=y*log10(x);//¿ìËÙÃÝ£» int s=ss;//ֻȡСÊýµãºó£» long long u=tp(x,y); cout<<"Case "<<k++<<": "<<setw(3) <<setfill('0') <<(int)(pow(10,ss-s)*100)<<" "<<setw(3) <<setfill('0') <<u<<endl;//控制输出格式 用printf会更短。 } }