题意:给出n,求n!的位数。
分析:首先想到的是用log10(n!)=log10(1)+log10(2)+...+log10(n)。但是由于log10运行时间较长,会超时,所以可以先将log10(1)~log10(maxn)存入数组,则省去了多次调用的时间浪费。但是有一种更好的做法就是利用stirling公式。
stirling公式:lim(n→∞) (n/e)^n*√(2πn) / n! = 1
虽然本题中的n并不是正无穷,但是求出的n!的位数还是不会出现误差的。所以我们直接以此公式整理出log10(n!)=log10(sqrt(2 * acos(-1) * n)) + n * log10(n / exp(1.0));
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <cmath> using namespace std; #define eps 1e-8 int main() { //freopen("t.txt", "r", stdin); int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); double ans = log10(sqrt(2 * acos(-1) * n)) + n * log10(n / exp(1.0)); printf("%d\n", (int)ans + 1); } return 0; }