Leading and Trailing LightOJ - 1282(数论,快速幂模板)

题意:给定两个数n,k 求n^k的前三位和最后三位

题解:后三位直接快速幂取模,注意不足三位要补前导零。前三位的话还是有些技巧的,首先任何数都可以写成n^k=10^(x+y),其中x是整数,y是个小数,而x之决定了这个数的位数,y才是决定这个数每一位的关键,所以我们求出y,然后10^y*100就是我们的前三位。

AC代码:

#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <cmath>
#include <queue>
#include <algorithm>
#define int long long
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=1e6+5;
int qmi(int a,int k,int mod){
	int ans=1;
	while(k){
		if(k&1)ans=ans*a%mod;
		k>>=1;
		a=a*a%mod;
		//cout<<k<<endl;
	}
	return ans%mod;
}
main(){
	int t,kase=1;
	cin>>t;
	while(t--){
		int n,k;
		cin>>n>>k;
		int ans2=qmi(n,k,1000);
		double y=(double)k*log10((double)n)-(int)((double)k*log10((double)n));
		int ans1=(int)(pow(10,y)*100);
		printf("Case %lld: %lld %03lld\n",kase++,ans1,ans2);
	} 
}

猜你喜欢

转载自blog.csdn.net/Alanrookie/article/details/107917885