python - 素因子分解不适用于具有重复因子的数字

标签 python prime-factoring

在这段代码中,用户必须输入一个区间,程序必须计算该区间内每个数字的素因数分解。

但是,我无法打印具有重复因数的数字(例如 4、8 和 9)的正确素因数分解。

我尝试使用 while 循环,但我无法正确使用它,并且我的代码只是不停地运行。

问题要求:求给定区间[a,b]内所有整数的质因数分解。

范围(3,10)的预期输出:

3=3
4=2*2
5=5
6=2*3
7=7
8=2*2*2
9=3*3
10=2*5

我的代码:

a, b = map(int, input().split())
j = [] #list for prime numbers
lst = [] #list for factors for numbers in range(a,b)


# prime numbers
for number in range(2, b+1):
    for i in range(2, number):
        if number % i == 0:
            break
    else:
        j.append(number)

#factors
for c in range(a, b+1):
    lst = []
    for i in j:
        k = c % i
        if k == 0:
            lst.append(i)

    print(f'{c}=', end='')
    print(*lst, sep='*')

范围 (3,10) 的我的代码输出:

3=3
4=2
5=5
6=2*3
7=7
8=2
9=3
10=2*5

非常感谢我能得到的任何反馈,谢谢!

最佳答案

关闭。您必须循环直到不再为 0,而不是只检查一次 c % i

#factors
for c in range(a, b+1):
    print(f'{c}=', end='')
    lst = []
    for i in j:
        while i <= c and c % i == 0:
            c //= i
            lst.append(i)

    print(*lst, sep='*')

请注意,我必须将 cprint 移至循环顶部,因为我正在循环内修改 c 。直到我进行测试运行时我才注意到这一点。

关于python - 素因子分解不适用于具有重复因子的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71756236/

相关文章:

python - 是什么导致 http 请求覆盖 ​​file.write() 创建的内部缓冲区?

c++ - C 或 C++ : Libraries for factoring integers?

java - 为什么这两种算法的运行时间存在差异?

python - 质因数,帮助理解平方根的用途

python - 从动态字典创建矩阵

python - 如何删除所有子元素?

Python + CGI脚本无法访问环境变量

python - 添加列作为 pandas 中每个列元素的出现次数

java - Combitronics 和质因数分解 : Calculate num of Pairs of (m, n) 其中 GCD(m,n)=x

c++ - 质数保理,无 IO