【ZOJ2277】The Gate to Freedom

BUPT2017 wintertraining(16) #4 E
ZOJ - 2277

题意

输出(n^n)的首位的数字。

题解

用科学计数法表示(n^n=kcdot 10^b),那么(n log_{10} n=log_{10} k+b),b就是(n^n)的位数,因此是(lfloor n log_{10} n floor)
(k=10^{n log_{n}-b})取k的整数部分即可。
我比赛的时候没想到这样做,于是转为小数,再用快速幂暴力做的。

代码

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
int n;
int main() {
	while(~scanf("%d",&n))
		printf("%d
",(int)pow(10,n*log10(n)-(int)(n*log10(n))));
	return 0;
}

快速幂暴力

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#define ll long long
using namespace std;
double pow(double a,int b){
	double ans=1;
	while(b){
		if(b&1){
			ans=ans*a;
		}
		a=a*a;
		while(a<0.01)a*=10;
		b>>=1;
	}
	return ans;
}
int main() {
 	int n;
	while(~scanf("%d",&n)){
		double t=n;
		while(t>=1)t/=10;
		double ans=pow(t,n);
		while(ans<1)ans*=10;
		
		printf("%d
",(int)ans);
	}
	return 0;
}
原文地址:https://www.cnblogs.com/flipped/p/6372329.html