1282 - Leading and Trailing
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 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的前三位数和后三位数;
后三位好求,直接快速幂取模,但是要注意可能出现前导为0的情况,输出时应用格式控制;
前三位就要用到对数函数:设n^k=a*10^m,(a<10) 那么a就表示n^k的缩小版,求出来直接放大100倍就行了;
AC代码:
#include<cstdio>
#include<cmath>
typedef long long LL;
LL quickpow(LL base,LL y,LL mod)
{
LL res=1;
while(y)
{
if(y&1)
{
res=res*base%mod;//不能写成res*=base%mod;
}
y>>=1;
base=base*base%mod;
}
return (res%mod+mod)%mod;
}
int main()
{
LL T,N,bef,K,Kase=0;
double pre=0.0;
scanf("%lld",&T);
while(T--)
{
scanf("%lld %lld",&N,&K);
pre=1.0*K*log10(N*1.0);
pre=pre-(LL)pre;
bef=quickpow(N,K,1000LL);
printf("Case %lld: %lld %03lld\n",++Kase,(LL)(pow(10.0,pre)*100),bef);//输出格式要注意 不够要补0
}
return 0;
}
2016.12.9
AC代码:
#include<cstdio>
#include<cmath>
typedef long long LL;
LL Pow_Mod(LL base,LL y,LL MOD) {
LL ans=1;
while(y) {
if(y&1) ans=ans*base%MOD;
y>>=1; base=base*base%MOD;
}
return ans;
}
int main() {
LL T,Kase=0; scanf("%lld",&T);
while(T--) {
LL N,K; scanf("%lld%lld",&N,&K);
LL lest=Pow_Mod(N,K,1000); double tem=K*log10(N);
LL most=100*pow(10.0,tem-(LL)(tem));
printf("Case %lld: %lld %03lld\n",++Kase,most,lest);
}
return 0;
}