Big Number (Stirling formula) factorial digit calculation

 

The question roughly means to enter a T, then enter n in the next T line and calculate the number of digits of the factorial of n in each line

Problem-solving ideas: If this problem is not a large number, you can use the logarithmic function property: log10(1*2*3*4*5...)=log10(1)+log10(2)...

Attach the code, note that sum is double

intmain ()
{
    ios::sync_with_stdio(false);
    cin>>T;
    double sum;//注意double
    while(T--)
    {
        cin>>n;
        sum=0.0;
        if(n>1)
        {
            for(long long i=1;i<=n;i++)
            {
                sum+=log10(i);
            }
        }
        if(n==1) sum=1;
        cout <<ceil(sum)<<endl; // Function to round up 
    }
     return  0 ;

}

The result is TLE. . .

 

The correct solution is to use Stirling's formula:

Attached code:

const double PI=3.141592654;
const double e=2.71828182846;

int T,n;
int main()
{
    ios::sync_with_stdio(false);
    cin>>T;
    while(T--)
    {
        cin >> n;
        int ans= 0 ;
        if (n> 3 ) ans=( int )(log10(( 2 *PI*n))/ 2 +n*log10((n/e))+ 1 );
        else ans= 1 ;
        cout<<ans<<endl;;
    }
    return 0;
}

Stirling formula more accurate method: https://www.cnblogs.com/stonehat/p/3603267.html

 

Another good way of thinking (maybe...): http://www.cnblogs.com/yuzhaoxin/archive/2011/11/19/2205221.html

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325339917&siteId=291194637