计算 100 阶乘中的数字和

标签 c factorial

编辑 - 更改标题以匹配实际问题陈述。

我正在编写一个计算 100 位数字总和的函数!但我似乎有两个大问题。

  1. 100的实际结果! is only accurate to the first few numbers (actual result is 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000)

  2. 我将所得数字的数字相加的方法没有输出正确的结果。

这是我当前的代码:

void factorialSum()
{
    double fact100 = factorial(100);
    double suma = 0;

    printf("100! is equal to: %.0f", fact100);

    while (fact100 > 0)
    {
        double temporal = fmod(fact100, 10);
        suma = suma + temporal;
        fact100 = fact100/10;
    }
    printf("\nThe sum of all digits in 100! is: %.0f", suma);
}

函数 factorial() 定义为:

double factorial (double n)
{
    double mult = 1;
    double i = n;

    while (i>=1)
    {
        mult *= i;
        i = i - 1;
    }
    return mult;
}

The program outputs 93326215443944102188325606108575267240944254854960571509166910400407995064242937148632694030450512898042989296944474898258737204311236641477561877016501813248 as a result for 100!并说它的数字之和等于 666。

感谢任何帮助,谢谢。

最佳答案

在 C 中,double 通常具有 53 位精度,对应于 16 或 17 位精度。因此,一旦超出 22!double 就无法再表示准确的结果,如以下代码所示。请注意,在 23! 处,尾随零消失了,因为 double 不再代表准确的值。

#include <stdio.h>
#include <stdint.h>

int main( void )
{
    double y;

    y = 1;
    for ( int i = 2; i < 30; i++ )
    {
        y *= i;
        printf( "%2d %32.0lf\n", i, y );
    }
}

这是程序的输出

 2                                2
 3                                6
 4                               24
 5                              120
 6                              720
 7                             5040
 8                            40320
 9                           362880
10                          3628800
11                         39916800
12                        479001600
13                       6227020800
14                      87178291200
15                    1307674368000
16                   20922789888000
17                  355687428096000
18                 6402373705728000
19               121645100408832000
20              2432902008176640000
21             51090942171709440000
22           1124000727777607680000
23          25852016738884978212864
24         620448401733239409999872
25       15511210043330986055303168
26      403291461126605650322784256
27    10888869450418351940239884288
28   304888344611713836734530715648
29  8841761993739700772720181510144

如果您想计算 100! 的精确值,您需要使用数字数组(又名 bignums )来进行计算。您可以找到要使用的 bignum 库,也可以自己实现 bignum 乘法。关于 bignums 的维基百科文章提供了 pseudocode用于计算阶乘。

关于计算 100 阶乘中的数字和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28032886/

相关文章:

javascript - 阶乘递归调用中的逻辑

c++ - 创建操作系统关闭按钮? (WinAPI)

c++ - 递归删除预处理器宏

c - 当我把它放在一个 char 数组中时,unsigned char 没有出现在 printf 中

c - 在 C 中使用 OpenSSL API 进行加密

algorithm - 当 f(n) = O(n!) 且 k=n*(n-1) 时 f(k) 的复杂度

c++ - 如何换出内存块?

python - 带有 "while"循环的 PYTHON 上的基本 FACTORIAL 算法

javascript - 阶乘的最低有效非零数字

Haskell:在连续传递风格中完全定义阶乘的问题