首先,定义:
A polydivisible number is an integer number where the first n digits of the number (from left to right) is perfectly divisible by n. For example, the integer 141 is polydivisible since:
- 1%1==0
- 14%2==0
- 141%3==0
我正在开发一个递归可整除的检查器,给定一个数字,它将检查该数字是否可整除,如果不是,则递归检查之后的所有其他数字,直到它达到可整除的数字。 不幸的是,我的代码没有按照我想要的方式工作。有趣的是,当我输入一个已经可整除的数字时,它会完成其工作并输出该可整除的数字。当我输入一个不可整除的数字(例如 13)时,就会出现问题。下一个可整除的数字应该是 14,但程序无法输出它。相反,它会陷入无限循环,直到内存耗尽。 这是我的代码:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
else:
return num
else:
print("Number must be non-negative")
return None
我假设问题出现在 while 循环内的 else 语句中,其中,如果数字不能被整除,则程序将 i 重置为 0,并在原始数字上加 1这样它就可以开始检查新号码。然而,正如我所解释的,它并没有按照我想要的方式工作。 知道代码可能有什么问题,以及如何确保它在达到 1(例如 14)时停止并输出正确的可整除数?
(另请注意,此检查器只应该接受非负数,因此初始 if 条件)
最佳答案
错误是你在增加 num 后没有更新数字。
这是工作代码:
def next_polydiv(num):
number = str(num)
if num >= 0:
i = 1
print(i)
while i <= len(number):
if int(number[:i]) % i == 0:
i += 1
print(i)
else:
i = 1
print(i)
num += 1
print(num)
number = str(num) # added line
else:
return num
else:
print("Number must be non-negative")
return None
关于python-3.x - 尽管之前的实现工作正常,但可整除计算器仍失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62452318/