求阶乘欧拉函数_欧拉计画20:阶乘总和

求阶乘欧拉函数

阶乘和 (Factorial Digit Sum)

Warning: Please only read this post, when you are absolutely sure, that you don’t want to take part in the challenge that is Project Euler. My posts will spoil the solution for you. I’m posting my solutions to show one possible way on how to solve the problems in case you want to compare your solutions with mine or are stuck and gave up on solving the problem.

警告:只有在绝对确定不希望参加Euler项目这一挑战时,才请阅读此文章。 我的帖子将为您破坏解决方案。 我要发布解决方案,以显示一种解决问题的可能方法,以防您想将自己的解决方案与我的解决方案进行比较,或者被卡住而放弃解决问题。

Problem 20 has you calculate the digit sum of “100!”. “100!” is the factorial of 100 and equates to 1 * 2 * 3 * … * 99 * 100. And from this product we want to know the digit sum. We have already calculated the digit sum of another long integer in a previous Project Euler problem (Problem 16),  therefore I’m going to keep this post rather short.

问题20让您计算出数字总和为“ 100!”。 “ 100!” 是100的阶乘,等于1 * 2 * 3 *…* 99 *100。从这个乘积中,我们想知道数字总和 。 我们已经在上一个Project Euler问题( 问题16 )中计算了另一个长整数的数字总和,因此,我将使这篇文章简短些。

Since we don’t have to worry, that 100! overflows our range for integers in Python, we can simply calculate 100! and store it regularly in a variable. We are going to use the same trick as in Problem 16 to calculate the digit sum. We use the built-in function sum, that returns the sum of a given list. And the list we are going to give as parameter is the single digits of 100!. This is produced by using another built-in function called map(), which applies a given function, in our case int(), to a list. This parameter is going to be the str() of 100!, which can be seen as a list of single characters. This chain of function calls ultimately gives us the digit sum.

既然我们不用担心,那100! 在Python中溢出了整数范围,我们只需计算100! 并定期将其存储在变量中。 我们将使用与问题16中相同的技巧来计算数字总和。 我们使用内置函数sum ,该函数返回给定列表的总和。 我们将作为参数给出的列表是100!的个位数。 这是通过使用另一个称为map()的内置函数产生的,该函数将给定函数(在我们的例子中为int())应用于列表。 该参数将是100!的str(),可以看作是单个字符的列表。 这个函数调用链最终为我们提供了数字总和。

So here’s the code:

所以这是代码:

"""Digit sum of 100!"""

def euler20():
    """Calculates solution of Problem 20"""
    counter = 1
    for i in range(2, 101):
        counter *= i
    counter = sum(map(int,str(counter)))
    print("Result: " + str(counter))

euler20()

Problem 20 was really easy to solve, especially since we already knew how to quickly calculate the digit sum of a given number and didn’t have to worry for an overflow caused by storing 100!. The processing speed was sufficient and not really interesting, considering the simplicity of the problem solution.

问题20确实很容易解决,特别是因为我们已经知道如何快速计算给定数字的数字总和,而不必担心存储100!会导致溢出! 考虑到问题解决方案的简单性,处理速度足够快,而且并不是很有趣。

翻译自: https://www.pybloggers.com/2015/06/project-euler-20-factorial-digit-sum/

求阶乘欧拉函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值