HDU1018 巧用数学思维

题目需要求出一个数的阶层的位数

只是求位数,并不需要求出这个数具体的阶层是多少

例如求10的阶层位数

10!= 10*9*8*7*6*5*4*3*2*1

令 log10 (10*9*8*7*6*5*4*3*2*1)= m   即10^m=10!  (那么m向下取整加1 即为所求)

运用高中学到的对数公式可化简为:

log10(10)+log(9)+log(8)+......+log(1)=m

m可在O(n)时间内求得  很容易

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    int amount,x;
    double sum;
    cin>>amount;
    while(amount--)
    {
        cin>>x;
        if(x==0 || x==1)
        {
            cout<<1<<endl;
            continue;
        }
        sum=0;
        while(x!=1)
        {
            sum+=log10(x);
            x--;
        }
        cout<<(int)sum+1<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/artistkeepmonkey/article/details/86713665
今日推荐