求10000以内n的阶乘

GitHub跳转原题关系图返回列表

调用 math.factorial 计算 10000 以内的阶乘,并兼容大整数输出限制。

OJ: noi_openjudge

题目 ID: ch0106-14

难度:入门

标签:高精度数学python

日期: 2026-07-30 23:01

题意

输出 n!n!,其中 0n100000\leqslant n\leqslant10000

思路

math.factorial(number) 用 Python 任意精度整数计算阶乘。Python 3.11 及更高版本默认限制极长整数转为字符串的位数,代码在该接口存在时调用 set_int_max_str_digits(0),使 10000!10000! 可以完整输出;Python 3.10 没有该接口,会自动跳过。

代码

Python代码

python
import math
import sys

if hasattr(sys, "set_int_max_str_digits"):
    sys.set_int_max_str_digits(0)

number = int(input())
print(math.factorial(number))

C++代码

cpp
/* 高精乘单精 */
#include <cstdio>

int a[10000000] = {1};
int cnt = 1;
int n;
int main(){
    scanf("%d",&n);
    int i,j,k;
    for(i=1;i<=n;i++){
        for(j=0;j<cnt;j++){
            a[j] *= i;
        }
        int pre =0;
        for(j=0;j<cnt;j++){
            int t = (a[j] + pre) % 10;
            pre = (a[j] + pre) / 10;
            a[j] = t;
        }
        while( pre != 0){
            a[cnt++] = pre %10;
            pre /=10;
        }
    }
    for(i=cnt-1;i>=0;i--)
        printf("%d",a[i]);
    return 0;
}

复杂度

输出本身需要与 n!n! 的十进制位数成正比的时间和空间。

总结

当结果极长时,除了计算本身,也要注意运行时对大整数输出的安全限制。