hdu1018 Big Number(斯特林公式)

本文介绍了两种计算阶乘位数的有效方法。一种是直接利用对数特性进行累加,另一种则采用斯特林公式简化计算过程。通过这两种方法,可以避免大数运算带来的问题,实现快速准确地计算。

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


http://acm.hdu.edu.cn/showproblem.php?pid=1018

题意:求一个数阶乘的位数。


思路:求一个数的位数,普通的for对这么大的数先求出来是不现实的,所以就有了下面的公式:

n的位数 = (int)log10(n)+1。

那n!的位数就是(int)log10(1)+(int)log10(2)+(int)log10(3)+...+(int)log10(n)+1。


#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <math.h>

using namespace std;

typedef long long ll;
const int N = 2003;

int main()
{
   // freopen("in.txt", "r", stdin);
    int t, x;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &x);
        double sum = 0;
        for(int i = 1; i <= x; i++)
            sum+=log10(i);
        printf("%d\n", (int)sum+1);
    }
    return 0;
}


斯特林公式:n! = sqrt(2πn)*(n/e)^n。

换成以10为底的对数就是:

log10(n!) = 0.5*log10(2πn)+n*log10(n)-n*log10(e)。

注意下π和e的值,输出记得转化成int。

很简单的,自己动手算算就行。



#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <math.h>

using namespace std;

typedef long long ll;
const int N = 2003;
const double PI = 3.1415926535897932385;
const double e = 2.7182818284590452354;

int main()
{
   // freopen("in.txt", "r", stdin);
    int t, n;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%d", &n);
        double sum = 0;
        sum = 0.5*log10(2*PI*n)+n*log10(n)-n*log10(e);
        printf("%d\n", (int)sum+1);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值