原理:
上面那条就是斯特灵公式,在计算n!的时候,这条公式就近似等于n!,其中n越大,两个数值越接近
作用:
1、估算n的阶层(这个作用较小,毕竟最多保存在long long中)
2、估算n!的位数,其中 要知道一条数学公式 log10(num)+1等于num的位数
3、估算n!是另一个数的多少倍
下面直接来一道例题,来看看这个公式要怎样用
例题链接:hdu1018 Big Number
例题:
Problem Description
In many applications very large integers numbers are required. Some of these applications are using keys for secure transmission of data, encryption, etc. In this problem you are given a number, you have to determine the number of digits in the factorial of the number.
Input
Input consists of several lines of integer numbers. The first line contains an integer n, which is the number of cases to be tested, followed by n lines, one integer 1 ≤ n ≤ 10
7 on each line.
Output
The output contains the number of digits in the factorial of the integers appearing in the input.
Sample Input
21020
Sample Output
719
题目大意:
就是要求你输入一个数,求它的阶层的位数
分析:
10^7次方的阶层,直接模拟是不可能实现的了,那么只有用数学公式:
1、res = (int)log10(n!)+1 = (int)log10(1*2*3...*n)+1
= int ( log(10)1 + log10(2) + log10(3) + ... + log10(n) ) + 1;
2、分解斯特灵公式,res = (int)log10(n!)+1 = (int)log10(√(2πn) * (n/e)^(n))+ 1
= (int)log10(2*n*pi)/2+n*log10(n/e) + 1
题解:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;
const double pi = acos(-1.0);
const double e = exp(1);
int main(){
int n;
scanf("%d",&n);
for(int t = 0; t < n; t++){
int tmp;
scanf("%d",&tmp);
printf("%d\n",(int)(log10(2*tmp*pi)/2+tmp*log10(tmp/e) + 1));
}
return 0;
}
知道公式之后这些题就变得很清晰了,但是目前我只找到两道用这个公式的题目,下面贴出
题解就不贴了,很简单10行代码左右就可以做出来了
如果有眼前一亮的题目或者解答欢迎和楼主讨论 ε=ε=ε=┏(゜ロ゜;)┛ 楼主的QQ486291187.
PS:谁还找到这个公式的题目欢迎补充啊啊啊o((>ω< ))o