LightOJ - 1282
http://lightoj.com/login_main.php?url=volume_showproblem.php?problem=1282
题目
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
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的前三位和后三位,后三位要补全,也就是说后三位如果为012
则要输出012,不能只输出12
思路
后三位用快速幂就完事了
ll quick_pow(ll a,ll b)
{
ll ans=1;
while(b){
if(b&1) ans=ans*a%mod;
a=a*a%mod;
b>>=1;
}
return ans;
}
主要是求前三位
这里我们这样想:
对于 y = log10(x) 这样一个函数,y的值域是(-∞,+∞).
那么对于题目中给定的数字 nk ,必然存在 y = log10(x)=nk
两边同时取对数,那么有x = log10(nk)= klog10(n)
这个x分为整数部分int和小数部分double
整数部分的值是nk的位数-1
小数部分的值是nk 除以 (10的整数部分次方)。
打个比方,nk等于123456
那么x的整数部分int有,xint=1e5
x的小数部分double有,xdouble =1.23456
然后这里我们取x的小数部分,乘100强转成整型就是前三位的值了。
代码
#include<cstdio>
#include<cmath>
typedef long long ll;
using namespace std;
ll n,k;
const ll mod=1000;
ll quick_pow(ll a,ll b)
{
ll ans=1;
while(b){
if(b&1) ans=ans*a%mod;
a=a*a%mod;
b>>=1;
}
return ans;
}
int main()
{
int t;
scanf("%d",&t);
for(int i=1;i<=t;i++)
{
scanf("%lld %lld",&n,&k);
double p=k*log10(n);
p=p-(int)p;
printf("Case %d: %lld",i,(ll)(pow(10,p)*100));
printf(" %03lld\n",quick_pow(n,k));
}
return 0;
}