BIT1046 Leftmost Digit

题意,给一个n(<10^7)

求n!的最高位数字

比如3!=6 最高位就是6

解法:

lgn!=lg1+lg2+....+lgn=temp

这里如果用O(n)的累加算lgn!就会因为样例数可能达到1000个

10^7*10^3>10^8而超时

有斯特林公式


lgn!=log10(sqrt(2*PI*n*1.0))+n*log10(n*1.0/e)

算出lgn!后,比如对于

n=5

lg5!=2.07918

由于整数部分与最高位无关

剪掉变成0.07918

10^0.07918=1.19999

于是最高位就是1

由于斯特林公式在n比较小的时候误差较大,所以在n较小时可以用O(n)的方法算lgn!

上代码

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<math.h>
using namespace std;
#define PI acos(-1.0)
#define e exp(1.0)
int main()
{
	int total;
	scanf("%d",&total);
	while(total--)
	{
		int n;
		scanf("%d",&n);
		double temp;
		if(n>1000)
		{
			temp=log10(sqrt(2*PI*n*1.0));
			temp+=n*log10(n*1.0/e);
		}
		else
		{
			temp=0;
			for(int i=1;i<=n;i++)
			{
				temp+=log10(i*1.0);
			}
		}
		temp-=(int)temp;
		temp=pow(10.0,1.0*temp);
		printf("%d\n",(int)temp);
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值