斯特林公式

摘自百度:

斯特林公式(Stirling's approximation)是一條用來取n的階乘近似值的數學公式。

形 式 :

或更精確的

 

1.  HDU1018:http://acm.hdu.edu.cn/showproblem.php?pid=1018

題意:求n!的位數。

題解:

暴力統計log10(1)+……log10(n),然後向上取整即可。

O(1)詢問的話,就用斯特林公式,對那個式子取log10。得到:log10(n!) = log10(sqrt(2*PI*n)) + nlog10(n/e) ,其中 PI 爲圓周率acos(-1.0),e 爲自然底數exp(1.0)。

代碼:

#include<bits/stdc++.h>
using namespace std;
const double e=exp(1.0);
const double PI=acos(-1.0);
int main()
{
	int T,n;
	double ans;
	scanf("%d",&T);
	while(T--)
	{
		scanf("%d",&n);
		ans=log10(sqrt(2.0*PI*n))+(double)n*log10((double)n/e);
		printf("%d\n",(int)ceil(ans));
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章