HDU 1018 Big Number(斯特林公式)

链接:传送门
题意:求n!的位数
思路:下面是三种情况,特别能体现知识面从窄到宽的巨大差别!


1.直接暴力,每当阶乘超过1e9时计算位数,最后再计算一次位数

/*************************************************************************
    > File Name: hdu1018t1.cpp
    > Author:    WArobot 
    > Blog:      http://www.cnblogs.com/WArobot/ 
    > Created Time: 2017年04月26日 星期三 20时46分26秒
 ************************************************************************/


// 暴力的做法
#include<bits/stdc++.h>
using namespace std;

typedef unsigned long long ull;
ull t,n;
const int maxn = 1e9;
int main(){
    while(cin>>t){
        while(t--){
            cin>>n;
            int cnt = 0;
            ull tmp = 1;
            for(int i=1;i<=n;i++){
                tmp *= i;
                while(tmp>=maxn){
                    tmp /= 10;
                    cnt++;
                }
            }
            while(tmp){
                tmp /= 10;
                cnt++;
            }
            printf("%d\n",cnt);
        }
    }
    return 0;
}

2.对于一个十进制数x,其位数为 log10(x) + 1 ,log10(n!) = log10(n) + log10(n-1) + ... + log10(1),也是暴力

/*************************************************************************
    > File Name: hdu1018t2.cpp
    > Author:    WArobot 
    > Blog:      http://www.cnblogs.com/WArobot/ 
    > Created Time: 2017年04月26日 星期三 21时09分14秒
 ************************************************************************/

// 一个十进制数位数的计算方法 log10(x) + 1
#include<bits/stdc++.h>
using namespace std;

int t,n;
int main(){
    while(cin>>t){
        while(t--){
            cin>>n;
            double ans = 0;
            for(int i=1;i<=n;i++){
                ans += log10(i);
            }
            cout<<(long long)ans + 1<<endl;
        }
    }
    return 0;
}

3.根据斯特林公式可知a08b87d6277f9e2f69688e6c1c30e924b899f371.jpg 直接对后面的数求对数即可。

/*************************************************************************
    > File Name: hdu1018t3.cpp
    > Author:    WArobot 
    > Blog:      http://www.cnblogs.com/WArobot/ 
    > Created Time: 2017年04月26日 星期三 22时22分25秒
 ************************************************************************/

#include<bits/stdc++.h>
using namespace std;
#define PI 3.1415926535

int t,n;
int main(){
    scanf("%d",&t);
    while(t--){
        scanf("%d",&n);
        long long ans = (long long)( log10(sqrt(2*PI*n)) + n*log10(n/exp(1))  )+1;
        cout<<ans<<"\n";
    }
    return 0;
}

转载于:https://www.cnblogs.com/WArobot/p/6771442.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值