F - 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.
InputInput 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).
OutputFor 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 Input5
123456 1
123456 2
2 31
2 32
29 8751919
Sample OutputCase 1: 123 456
Case 2: 152 936
Case 3: 214 648
Case 4: 429 296
Case 5: 665 669
题意很简单,即为求出n^k的前三位数和后三位数,求出后三位数并不困难,只需要快速幂取模1000即可,
难点在于求前三位。
n^m一定可以转化为10^a,将a分为整数部分x和小数部分y,则10^a=10^x*10^y,因为0=<y<1,所以1=<10^y<10,由此可见,10^x即为科学计数法中的权值,所以10^y*100即为n^m的前三位数。
其中为分离a中的小数部分,用了小数模除函数 fmod();
#include<stdio.h>
#include <algorithm>
#include<iostream>
#include<string.h>
#include<vector>
#include<stdlib.h>
#include<math.h>
#include<queue>
#include<deque>
#include<ctype.h>
#include<map>
#include<set>
#include<stack>
#include<string>
#include<algorithm>
#define ll long long
#define INF 0x3f3f3f3f
using namespace std;
ll qpow(ll n,ll m)
{
ll ans=1;
while(m)
{
if(m&1)
ans=(ans*n)%1000;
n=(n*n)%1000;
m/=2;
}
return ans;
}
int main()
{
int t;
scanf("%d",&t);
for(int k=1;k<=t;k++)
{
ll n,m;
scanf("%lld %lld",&n,&m);
ll last=qpow(n%1000,m);
ll first=pow(10,fmod(m*log10(n*1.0),1))*100;
printf("Case %d: %03lld %03lld\n",k,first,last);
}
return 0;
}