首页 > 解决方案 > 我试图解决这个关于阶乘的问题,但它没有给出正确的答案

问题描述

这就是问题所在:编写一个 python 代码来查找小于 50,000 且等于其数字的阶乘总和的所有整数。例如:数字 7666 6= 7!+ 6!+ 6!+ 6!但是 145=1!+4!+5!

注意:我不允许使用任何特定的阶乘函数。

我的解决方案:

import math
from numpy import *
for i in range(5):
    for j in range(10):
        for k in range(10):
            for l in range(10):
                for m in range(10):
                    x=1*m+10*l+100*k+1000*j+10000*i
                    def fact(m):
                        fact=1
                        for i in range(1,m+1):
                            fact=fact*i
                        return fact
                    y=fact(i)+fact(j)+fact(k)+fact(l)+fact(m)
                    if x==y :
                        print(x)

标签: pythonfor-loopfactorial

解决方案


提示 1

这没有给你一个正确答案的原因是因为有时你的代码会被认为0是一个数字。

例如 fact(0)+fact(0)+fact(1)+fact(4)+fact(5)给出147

因为fact(0)1

提示 2

虽然您的迭代方式很有趣并且有些正确,但它是您的错误的根源。

尝试从 1 到 50000 正常迭代,然后以不同的方式计算数字的总和。

for i in range(50000):
    # ...

解决方案

由于这是 StackOverflow,我直接提供了一个解决方案。

使用这样的函数来查找数字的数字总和:

def fact(m):
    fact=1
    for i in range(1,m+1):
        fact=fact*i
    return fact

def sumOfFactOfDigits(x):

    # This function only works on integers
    assert type(x) == int

    total = 0

    # Repeat until x is 0
    while x:

        # Add last digit to total
        total += fact(x%10)

        # Remove last digit (always ends at 0, ie 123 -> 12 -> 1 -> 0)
        x //= 10

    return total


for i in range(50000):
    if i == sumOfFactOfDigits(i):
        print(i)

笔记

您应该将您的定义移到fact循环之外。


推荐阅读