What is the sum of the digits in the factorial of 20?
- 内容介绍
- 文章标签
- 相关推荐
本文共计616个文字,预计阅读时间需要3分钟。
题目:计算 100!(100 的阶乘)中各位数字的和。
解题思路:
100! 是一个非常大的数,直接计算它的值是不现实的。但我们可以通过计算各位数字的和来得到答案。由于每次乘法操作都可能导致数字的位数增加,因此我们需要一个有效的方法来避免直接计算每一位数。
解题步骤:
1.使用循环结构,从 1 到 100 对所有数字进行连乘。
2.在每次连乘操作后,计算结果的位数。
3.将每个位数的和累加。
代码实现:
pythondef sum_of_digits_in_factorial(n): factorial=1 for i in range(1, n + 1): factorial *=i # 将阶乘数转换为字符串,以便计算位数 factorial_str=str(factorial) # 计算当前位数的和并累加到总和中 digit_sum +=sum(int(digit) for digit in factorial_str) return digit_sum计算 100! 中各位数字的和digit_sum=sum_of_digits_in_factorial(100)print(The sum of the digits in 100! is:, digit_sum)
请注意,这段代码计算的是 100! 中各位数字的和,而不是 100! 的实际值。由于 100! 的数值极大,直接计算会消耗大量内存和计算资源。
Problem 20
n! meansn× (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!
Answer:
648
Completed on Thu, 27 Oct 2016, 14:17
题解:高精度阶乘。
代码:
using namespace std;
const int MAXN=40000;//如果是10000的阶乘,改为40000就够了
int f[MAXN];
int main() //HDU 1042
{
int i,j,n;
int ans=0;
while(scanf("%d",&n)!=EOF)
{
memset(f,0,sizeof(f));
f[0]=1;
for(i=2;i<=n;i++)
{
int c=0;
for(j=0;j<MAXN;j++)
{
int s=f[j]*i+c;
f[j]=s%10;
c=s/10;
}
}
for(j=MAXN-1;j>=0;j--)
if(f[j]) break;//忽略前导0
for(i=j;i>=0;i--) {
printf("%d",f[i]);
ans+=f[i];
}
printf("\n");
cout<<ans<<endl;
}
return 0;
}
本文共计616个文字,预计阅读时间需要3分钟。
题目:计算 100!(100 的阶乘)中各位数字的和。
解题思路:
100! 是一个非常大的数,直接计算它的值是不现实的。但我们可以通过计算各位数字的和来得到答案。由于每次乘法操作都可能导致数字的位数增加,因此我们需要一个有效的方法来避免直接计算每一位数。
解题步骤:
1.使用循环结构,从 1 到 100 对所有数字进行连乘。
2.在每次连乘操作后,计算结果的位数。
3.将每个位数的和累加。
代码实现:
pythondef sum_of_digits_in_factorial(n): factorial=1 for i in range(1, n + 1): factorial *=i # 将阶乘数转换为字符串,以便计算位数 factorial_str=str(factorial) # 计算当前位数的和并累加到总和中 digit_sum +=sum(int(digit) for digit in factorial_str) return digit_sum计算 100! 中各位数字的和digit_sum=sum_of_digits_in_factorial(100)print(The sum of the digits in 100! is:, digit_sum)
请注意,这段代码计算的是 100! 中各位数字的和,而不是 100! 的实际值。由于 100! 的数值极大,直接计算会消耗大量内存和计算资源。
Problem 20
n! meansn× (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!
Answer:
648
Completed on Thu, 27 Oct 2016, 14:17
题解:高精度阶乘。
代码:
using namespace std;
const int MAXN=40000;//如果是10000的阶乘,改为40000就够了
int f[MAXN];
int main() //HDU 1042
{
int i,j,n;
int ans=0;
while(scanf("%d",&n)!=EOF)
{
memset(f,0,sizeof(f));
f[0]=1;
for(i=2;i<=n;i++)
{
int c=0;
for(j=0;j<MAXN;j++)
{
int s=f[j]*i+c;
f[j]=s%10;
c=s/10;
}
}
for(j=MAXN-1;j>=0;j--)
if(f[j]) break;//忽略前导0
for(i=j;i>=0;i--) {
printf("%d",f[i]);
ans+=f[i];
}
printf("\n");
cout<<ans<<endl;
}
return 0;
}

