python-3.x - 尽管之前的实现工作正常,但可整除计算器仍失败

标签 python-3.x

首先,定义:

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/

相关文章:

python - 皮查姆 : Failed to Create Interpreter Error occurred: Permission Denied - Windows 10

python - 从订阅者调用远程过程并解决 asyncio promise

python - 异常值: 'User' object has no attribute 'update' thrown in DJANGO ORM

python - 如何使用python获取wlan设备名称?

python-3.x - Python : How to print the box, 盒须图中的 mustache 和离群值?

Python 异步/aiohttp : ValueError: too many file descriptors in select() on Windows

Python 3 除了 TypeError 不工作

python-3.x - 从 pandas xlsxwriter 打开 Excel (XLSX) 文件时出错

python - 运行 python3 -bb 时,为什么 set([b'foo', u'foo']) 失败但 set([b'foo', u'bar']) 成功?

python - 如何在 AWS EC2 实例上安装 Python 3?