快速幂 LightOJ 1282 - Leading and Trailing
题意就是求n的k次方的前三位和后三位
- 后三位快速幂取模就行。
- 前三位,首先pow(n,k)=pow(10,k*lg(n)),此时可以看出pow(n,k)的值的位数是由k *lg(n)的整数部分决定,而值是由其小数部分决定,因此只取前三位的话让k *lg(n)的小数部分在加上2即可,然后再将其转化为整数形式,舍去后面的小数。 即pow(10,2+fmod(k *log10(n),1)) fmod(k *log10(n),1)的作用便是得出k *lg(n)的小数。
#include <iostream>
#include <algorithm>
#include <cstring>
#include <stdio.h>
#include <cmath>
using namespace std;
typedef long long ll;
int quick_pow(int a,int b)
{
ll r=1,base=a;
while(b)
{
if(b&1)
r=(r*base)%1000;
base=(base*base)%1000;
b>>=1;
}
return r;
}
int main()
{
int T,n,k;
cin>>T;
for(int cas=1;cas<=T;cas++)
{
cin>>n>>k;
int p=quick_pow(n,k);
int q=pow(10,2+fmod(k*log10(n),1));
printf("Case %d: %d %03d\n",cas,q,p);
}
return 0;
}