zoukankan      html  css  js  c++  java
  • HDOJ(1018)

    Big Number

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
    Total Submission(s): 34743    Accepted Submission(s): 16478


    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 ≤ 107 on each line.
     
    Output
    The output contains the number of digits in the factorial of the integers appearing in the input.
     
    Sample Input
    2
    10
    20
     
    Sample Output
    7
    19
     

    数学公式推导

    方法一:

    ①:10^M < n!   <10^(M+1)  若求得M,则M+1即为答案。

    对公式①两边以10为底取对数

    M < log10(n!) < M+1

    因为 log10(n!)=log10(1)+log10(2)+……+log10(n)

    可用循环求得M+1的值

    #include<iostream>
    #include<cstdio>
    #include<cmath>
    using namespace std;
    int main()
    {
        int T;
        cin>>T;
        while(T--)
        {
            int n;
            cin>>n;
            double ans=0;
            for(int i=1;i<=n;i++)
            {
                ans+=log(i)/log(10);
            }
            cout<<(int)ans+1<<endl;
            
        }
        return 0;
    }

    方法二:斯特林公式
    n! ≈ sqrt(2*n*pi)*(n/e)^n

    则 M+1=(int)(0.5*log(2.0*n*PI)+n*log(n)-n)/(log(10.0)) )+1;

    #include<iostream>
    #include<cstdio>
    #include<cmath>
    using namespace std;
    const double PI=3.1415926;
    int main()
    {
        int T;
        cin>>T;
        while(T--)
        {
            int n;
            cin>>n;
            double ans;
            ans=(0.5*log(2.0*n*PI)+n*log(n)-n)/(log(10.0));
            cout<<(long)ans+1<<endl; 
        }
        return 0;
    }

     Java:

    import java.util.Scanner;
    public class Main{
        static Scanner cin=new Scanner(System.in);
        static final int MAXN=10000005;
        static int[] res=new int[MAXN];
        public static void main(String[] args){
            double pre=Math.log(1.0);
            res[1]=(int)pre+1;
            for(int i=2;i<=10000000;i++)
            {
                pre+=Math.log10((double)i);
                res[i]=(int)pre+1;
            }
            int T=cin.nextInt();
            while(T--!=0)
            {
                int n=cin.nextInt();
                System.out.println(res[n]);
            }
        }
    }
  • 相关阅读:
    os.fork()
    解决方案:WindowsError: [Error 2]
    Python遍历文件夹和读写文件的方法
    导航帖
    IDEA后缀补全及快捷键
    Codeforces-Round#614 Div2
    图论算法-欧拉回路 专题训练
    快速求出n!质因数的个数
    Codeforces-Round#589 Div2
    洛谷P3386二分图匹配
  • 原文地址:https://www.cnblogs.com/program-ccc/p/4690303.html
Copyright © 2011-2022 走看看