• poj1423


    题意:给出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));

    View Code
    #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;
    }
  • 相关阅读:
    特殊集合
    推箱子
    集合
    数组

    循环语句 练习题
    穷举与迭代
    循环语句
    练习题
    switch case
  • 原文地址:https://www.cnblogs.com/rainydays/p/2964799.html
Copyright © 2020-2023  润新知