为什么我的代码似乎不能处理奇数
why doesn't my code seemingly work with odd numbers
我正在尝试编写将数字分解为其质因数分解的代码。到目前为止它适用于偶数,但是当我尝试奇数时它会卡住。我不知道为什么会这样。我没有收到错误,它只是停止执行任何操作。
代码:
priemwaarde = 100
priemgetallen = []
nonpriemgetallen = []
for x in range(2,priemwaarde):
prime = True
for i in range(2,x):
if x % i == 0:
prime = False
if prime == False:
nonpriemgetallen.append(x)
else:
priemgetallen.append(x)
def PriemFactoren(getal):
factoren = []
a = getal
while a not in priemgetallen:
for priem in priemgetallen:
if a % priem == 0:
factoren.append(priem)
a = a / priem
a = int(a)
if getal not in priemgetallen:
factoren.append(a)
return factoren
print(PriemFactoren(56))
print(PriemFactoren(55))
如果你在你的while
循环中添加打印语句或调试断点,你会发现它被卡住了,因为a
的值最终是1,它无法找到它在 priemgetallen
.
想到的打破无限循环的快速解决方法是将其添加到列表中:
priemgetallen.append(1)
我想另一种选择是显式处理该值,所以这样的事情也应该打破无限循环:
def PriemFactoren(getal):
factoren = []
a = getal
while a not in priemgetallen:
#### Added lines
if a == 1:
break
#### End
for priem in priemgetallen:
if a % priem == 0:
factoren.append(priem)
a = a / priem
a = int(a)
if getal not in priemgetallen:
factoren.append(a)
return factoren
我正在尝试编写将数字分解为其质因数分解的代码。到目前为止它适用于偶数,但是当我尝试奇数时它会卡住。我不知道为什么会这样。我没有收到错误,它只是停止执行任何操作。
代码:
priemwaarde = 100
priemgetallen = []
nonpriemgetallen = []
for x in range(2,priemwaarde):
prime = True
for i in range(2,x):
if x % i == 0:
prime = False
if prime == False:
nonpriemgetallen.append(x)
else:
priemgetallen.append(x)
def PriemFactoren(getal):
factoren = []
a = getal
while a not in priemgetallen:
for priem in priemgetallen:
if a % priem == 0:
factoren.append(priem)
a = a / priem
a = int(a)
if getal not in priemgetallen:
factoren.append(a)
return factoren
print(PriemFactoren(56))
print(PriemFactoren(55))
如果你在你的while
循环中添加打印语句或调试断点,你会发现它被卡住了,因为a
的值最终是1,它无法找到它在 priemgetallen
.
想到的打破无限循环的快速解决方法是将其添加到列表中:
priemgetallen.append(1)
我想另一种选择是显式处理该值,所以这样的事情也应该打破无限循环:
def PriemFactoren(getal):
factoren = []
a = getal
while a not in priemgetallen:
#### Added lines
if a == 1:
break
#### End
for priem in priemgetallen:
if a % priem == 0:
factoren.append(priem)
a = a / priem
a = int(a)
if getal not in priemgetallen:
factoren.append(a)
return factoren