【发布时间】:2019-12-19 13:57:22
【问题描述】:
我正在尝试用 Python 编写质因式分解代码,这是我目前所做的:
# Prime Factorisation
while True:
try:
n, primes, factorisation, dividers, factors = abs(int(input('Enter an integer to find it\'s Prime Factorisation: '))), [], [], [], [] # Asks for input and assigns multiple variables and lists
break
except:
print('Please enter an integer.')
def isprime(num): # Checks if given number is prime
for i in range(1,num+1):
if num % i == 0:
factors.append(i)
return len(factors)== 2
for i in range(2,n+1):
if isprime(i):
primes.append(i)
for i in primes: # This code does the actual Prime Factorisation
while n % i == 0: # If n (The input the user gave) is divisible by i of list primes:
factorisation.append(n) # n is added to factorisation
dividers.append(i) # i is added to divisors
n /= i # n = n / i
output = str(dividers).replace(', ',' x ').replace('[','').replace(']','') # Pretties up the list dividers
print(str(factorisation[0]) + ' = ' + output) # Prints given value and divisors
该代码适用于像 256 这样的数字,但对于其他数字会给出奇怪的输出,请帮我找出错误,谢谢!
【问题讨论】:
-
“用其他数字给出奇怪的输出” - 它们有什么奇怪的?
-
factors应该是isprime函数定义中的局部变量