首页 > 解决方案 > Python没有像我预期的那样增加循环

问题描述

我有一些代码将整数作为输入并打印出该整数素因子的排序列表。

它几乎适用于所有数字,例如,当输入为 100 时,它将打印 [2, 2, 5, 5],而对于 1235632,它将输出 [2, 2, 3, 3, 343237]。

但是,对于更大的数字,它不会按顺序打印因子,我不确定这是我忽略的代码中未解决的问题还是其他问题。

例如,当我输入 1234567891011121314151617 时,它将输出 [3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 , 2, 2, 2, 2, 2, 2, 2, 3, 3, 43, 109, 104281, 1394027],这显然没有排序,我终生无法弄清楚为什么。

我正在使用我认为是最新版本的 pycharm。

无论如何,这是代码:

from math import floor
from math import sqrt

n = int(input("Enter a number to be split into its prime factors"))
FList = []
k = 1

while n != 1:
    k = k + 1
    s = floor(sqrt(n))

    if k > s:
        FList.append(int(n))
        break

    if n % k == 0:
        n = n/k
        FList.append(k)
        k = 1

print(FList)

编辑:只是为了澄清我宁愿修复程序,然后使用排序算法来帮助清理。

正如其他人指出的那样,大数字的因素完全是垃圾,所以我想现在的问题是为什么要打印这些数字。

标签: python

解决方案


问题是您正在使用/除法,其结果是浮点数:

6/2
# 3.0

当您尝试对大数进行因式分解时,除以第一个因数 (3) 后得到的结果是:

1234567891011121314151617 / 3
# 4.115226303370404e+23

这是四舍五入的,因为浮点数的精度有限。这就是为什么您现在可以多次将其除以 2。

您应该使用整数除法//,这将为您提供无限精度的精确商:

1234567891011121314151617 // 3
# 411522630337040438050539

因此,只需将您的代码更改为:

from math import floor
from math import sqrt

n = int(input("Enter a number to be split into its prime factors"))
FList = []
k = 1

while n != 1:
    k = k + 1
    s = floor(sqrt(n))

    if k > s:
        print('appending', n)
        FList.append(int(n))
        break

    if n % k == 0:
        n = n//k  # Use integer division here
        FList.append(k)
        k -= 1  # Try k again on next loop, no need to test smaller values again.

print(FList)

对于您尝试的数字,有一些很大的因素,因此可能需要很长时间......(实际上,它是 3*2*47*4993*584538396786764503...)


推荐阅读