HDOJ 1018 Big Number

来源:互联网 发布:洗衣机什么牌子好 知乎 编辑:程序博客网 时间:2024/06/05 09:26
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
21020
 

Sample Output
719
本题要求阶乘的位数,但经过尝试我们发现直接求阶乘会产生超时现象,本题中我们收获了一种专门求位数的方法,对于任意一个给定的正整数a,假设10^(x-1)<=a<10^x,那么显然a的位数为x位,又因为log10(10^(x-1))<=log10(a)<(log10(10^x)),即x-1<=log10(a)<x,则(int)log10(a)=x-1,即(int)log10(a)+1=x,即a的位数是(int)log10(a)+1,运用这种方法的妙处在于可以将乘积转化为和,一种方法我么就直接去遍历运算,第二种方法我们运用斯特林公式
方法一
////  main.cpp//  Bignumber////  Created by 张嘉韬 on 16/1/29.//  Copyright © 2016年 张嘉韬. All rights reserved.//#include <iostream>#include <cstring>#include <cmath>using namespace std;int main(int argc, const char * argv[]) {    int nu;    cin>>nu;    for(int t=1;t<=nu;t++)    {        int ans,n;        double temp;        temp=0;        cin>>n;        for(int i=1;i<=n;i++)        {            temp+=log10(i);        }        ans=temp;        ans++;        cout<<ans<<endl;    }    return 0;}
方法二
////  main.cpp//  bignumber////  Created by 张嘉韬 on 16/1/29.//  Copyright © 2016年 张嘉韬. All rights reserved.//#include <iostream>#include <cstring>#include <cmath>using namespace std;const double e=2.718281828;const double pi=3.1415926535;int main(int argc, const char * argv[]) {    int nu;    cin>>nu;    for(int t=1;t<=nu;t++)    {        int n,ans;        cin>>n;        double temp;        temp=0.5*log10(2*n*pi)+n*log10(n/e);        ans=temp;        ans++;        cout<<ans<<endl;    }    return 0;}


0 0