使用python。我的主因子分解器中的“打印”步骤有效,但它永远不会返回1,也不会生成列表。我的程序在哪里卡住了?
from math import ceil, floor, sqrt
primeList = []
primeFactorList = []
def primeList(x):
primeList = [2]
for n in range(2,x):
for p in primeList:
if n%p == 0:
break
elif p == primeList[-1]:
primeList.append(n)
return(primeList)
# Generates list of prime numbers less than x
def primeFactorizer(x):
primeFactorList = []
while x != 1:
for p in primeList(x):
if x%p == 0:
primeFactorList.append(p)
x = x/p
print(x)
break
return(primeFactorList)
# Generates list of (possibly duplicate) prime factors of x
print(primeFactorizer(36))
答案 0 :(得分:1)
primeList
返回的质数最多为x
,但小于x
。
如果primeFactorizer
中的x%p
是质数,则x
在for循环内永远不会为真,因此def factorize(number):
factors = []
for factor in range(2, number + 1):
while number % factor == 0:
factors.append(factor)
number //= factor
print(number)
if number == 1:
break
return factors
print(factorize(36))
永远不会改变。
忘记素数并测试每个数字以进行因式分解:
{{1}}