51nod-1130 N的阶乘的长度(斯特林)

本文介绍两种高效计算阶乘长度的方法:一种利用对数性质进行累加,时间复杂度为O(n);另一种使用斯特林公式,实现常数时间复杂度O(1)。文章提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目传送门: https://www.51nod.com/onlineJudge/submitList.html#!userId=11254&problemId=1130


给一个数N,求出N的阶乘的长度


一、取对数的做法

用对数的性质,将若干个数相乘改为若干对数相加的形式O(n)的时间复杂度

代码如下:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <stdio.h>
#include <string>
#include <cmath>
#define ll long long
#define mem(name,value) memset(name,value,sizeof(name))
using namespace std;
const int maxn = 1000005;
const int _max = 1000000;
int a[maxn];
int main()
{
    double n;
    cin >> n;
    double cnt = 0;
    for(double i=1;i<=n;i++){
        cnt += log10(i);
    }
    cout << (int)cnt + 1 <<endl;

    return 0;
}

二、斯特林公式

ans =  0.5 * log10(2.0 * PI * n) + n * log10(n * 1.0 / E) + 1;

o(1)的时间复杂度

代码如下:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <stdio.h>
#include <string>
#include <cmath>
#define ll long long
#define mem(name,value) memset(name,value,sizeof(name))
#define mod 1000000007
#define PI 3.1415926
#define E  2.718281828459
using namespace std;

const int maxn = 1005;

double getlg(double x){
    double cnt = 0;
    while(x > 10){
        x /= 10;
        cnt++;
    }
    x += cnt;
    return x;
}

int main() {
    int t;
    cin >> t;
    for(int i=0;i<t;i++){
        int n;
        cin >> n;
        ll res =  0.5 * log10(2.0 * PI * n) + n * log10(n * 1.0 / E) + 1;
        cout << res << endl;
    }

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值