Time Limit: 2 second(s) | Memory Limit: 32 MB |
You are given two integers: n and k, your taskis to find the most significant three digits, and least significant threedigits 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 leadingdigits (most significant) and three trailing digits (least significant). Youcan assume that the input is given such that nk contains atleast 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的前三位数和最后三位数(后三位很简单直接快速幂就好了);n,k比较大,所以化为
n^k=10^(k*log10(n));只求千三位数:
领p1=k*log10(n);
则其前三位数为(10^(p1-(int)p1+2));
代码:
#include <iostream>
#include <vector>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <stack>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
using namespace std;
int pow_mod(int a,int n,int mod)
{
int b=1;
a%=mod;
while(n)
{
if(n&1)b=(b%mod*a%mod)%mod;
a=(a%mod*a%mod)%mod;
n/=2;
}
return (b+mod)%mod;
}
int main()
{
int t,n,k;
scanf("%d",&t);
{
int cnt=0;
while(t--)
{
scanf("%d%d",&n,&k);
double p1=k*log10(n+0.0);
p1=p1-(long long int)p1;///去小数部分
p1=pow(10.0,p1+3);//前三位数主要看10的指数
int p=(int)p1;
while(p/1000)
{
p/=10;
}
int q=pow_mod(n,k,1000);
printf("Case %d: %d %03d\n",++cnt,p,q);
}
}
return 0;
}