在 C 中计算大数的阶乘 [英] Calculating factorial of large numbers in C

查看:32
本文介绍了在 C 中计算大数的阶乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 C 代码中,我想计算 1 到 100 范围内的数字的阶乘.对于小数字,该函数可以工作,但对于较大的数字(例如 100!),它返回不正确的结果.有没有办法在 C 中处理大数的阶乘?

In my C code, I want to calculate the factorial for numbers in the range 1 to 100. For small numbers, the function works, but for bigger numbers (for example 100!) it returns incorrect result. Is there any way to handle factorial of large numbers in C?

我使用的编译器是 gcc v4.3.3.我的代码如下:

The compiler I'm using is gcc v4.3.3. My code is as follows:

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

double print_solution(int);

int main(void)
{
        int no_of_inputs, n;
        int ctr = 1;

        scanf("%d",&no_of_inputs); //Read no of inputs

        do
        {
                scanf("%d",&n); //Read the input
                printf("%.0f
", print_solution(n));
                ctr++;  
        } while(ctr <= no_of_inputs);

        return 0;       
}

double print_solution(int n)
{
        if(n == 0 || n == 1)
                return 1;
        else
                return n*print_solution(n-1);
}

推荐答案

没有标准的 C 数据类型可以准确地处理大到 100! 的数字.如果使用 任意精度整数运算,您唯一的选择,要么通过库,要么通过自己.

No standard C data type will accurately handle numbers as large as 100!. Your only option if to use arbitrary precision integer arithmetic, either through a library or done by yourself.

如果这只是一些业余爱好项目,我建议您自己尝试一下.这是一种有趣的练习.如果这与工作相关,请使用预先存在的库.

If this is just some hobby project, I'd suggest trying it yourself. It's kind of a fun exercise. If this is work-related, use a pre-existing library.

您通常会获得的最大 C 数据类型是 64 位整数.100!是 10157 的数量级,至少需要 525 位才能准确存储为整数.

The largest C data type you'll normally get is a 64-bit integer. 100! is in the order of 10157, which takes at least 525 bits to store accurately as an integer.

这篇关于在 C 中计算大数的阶乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆