Leading and Trailing
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 |
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 |
题意:求n^k最开始的三个数字和最后的三个数字;
思路:最后的,显然快速幂%1000;注意输出需要前导0;
开始的用double,快速幂,每次将base在1-10之间,最后的答案*100转int就行了;
#include<iostream> #include<string> #include<cstring> #include<algorithm> #include<cstdio> using namespace std; #define ll long long #define esp 1e-13 const int N=1e4+10,M=1e6+50000,inf=1e9+10,mod=1000000007; int quickpow(int x,int y) { x%=1000; int sum=1; while(y) { if(y&1)sum*=x,sum%=1000; x*=x; x%=1000; y>>=1; } return sum; } void change(double &a) { while(a-10.0>=(-esp)) { a/=10; } } double pow1(double x,int y) { change(x); double ans=1.0; while(y) { if(y&1)ans*=x,change(ans); x*=x; change(x); y>>=1; } return ans; } int main() { int x,y,i,z,t; int T,cas; scanf("%d",&T); for(cas=1;cas<=T;cas++) { scanf("%d%d",&x,&y); double a=(double)x; double ans=pow1(a,y); int yu=quickpow(x,y); if(yu>=100) printf("Case %d: %d %d\n",cas,(int)(ans*100.0),yu); else if(yu>=10) printf("Case %d: %d 0%d\n",cas,(int)(ans*100.0),yu); else if(yu>=0) printf("Case %d: %d 00%d\n",cas,(int)(ans*100.0),yu); } return 0; }
时间: 2024-12-16 20:05:24