c++ - 阶乘数字和(无 BigInt)C++

标签 c++ factorial

我想弄清楚如何解决这个问题(欧拉计划):

n! means n × (n − 1) × ... × 3 × 2 × 1

For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800, and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!

使用 BigInt 不是一种选择,我正在尝试弄清楚如何仅使用 C++ 实现解决方案。

我想也许可以将大数字拆分为大约 7 位长的数组或类似的数组,然后处理它们,但我仍然无法弄清楚如何做到这一点..

提前致谢!

最佳答案

试试这个

#include "iostream"
#include "vector"

int n,remainder,sum;
int main ()
{   
    std::vector <int> digits(5000);    
    std::cin>>n;    
    digits[0]=1;
    digits[1]=1;
    for (int k=2;k<n+1;k++) {
        for (int i=1;i<=digits[0];i++) {
            digits[i]=digits[i]*k+remainder;
            remainder=0;
            if (digits[i]>9) {
                remainder=digits[i]/10;
                digits[i]%=10;
                if (i==digits[0])
                digits[0]++;
            }
        }
    }   
    for (int i=digits[0];i>=1;i--)
        sum+=digits[i];
    std::cout<<sum;
}

关于c++ - 阶乘数字和(无 BigInt)C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19334939/

相关文章:

c - 为什么这个阶乘递归程序不起作用?

JavaScript - 阶乘解释

转换 Bash 函数来计算 n!到C?

c - C 语言的 SPOJ 小阶乘程序

c++ - 反向代理的典型架构是什么?

c++ - 访问模板类型实例成员

c++ - 无法将子类 ... 转换为其私有(private)基类

c++ - 压缩 2 位整数的容器

c++ - 在另一个 COM 对象中创建一个 COM 对象

matlab - 200如何解决!在Matlab代码中?