我想弄清楚如何解决这个问题(欧拉计划):
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/