python - 我试图解决这个关于阶乘的问题,但它没有给出正确的答案
问题描述
这就是问题所在:编写一个 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)
解决方案
提示 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
循环之外。
推荐阅读
- angular - Angular:无法使用@Input第二次重置子组件中的值
- typo3 - TYPO3 服务不可用 (503)
- c++ - hiredis 消息未到达订阅的处理程序
- node.js - 我想在 puppeteer-cluster 中创建无限循环
- python - 为什么 Elif 在一些列表输入后打印?
- elasticsearch - 带有前缀查询的弹性搜索不区分大小写的查询
- javascript - 如何将图像 URL 替换为 JSON 对象中的图像标记?
- c# - SendNotifyMessage 和 WM_SETTINGCHANGE 不再工作了?(视窗 10)
- xpath - 如何找到 Chrome 插件元素的路径?
- jquery - 以编程方式调用 jquery 数据表单元格单击事件