Python 显示整数的素数因子的程序
我试图制作一个程序,将数字作为输入,并以列表格式显示该程序:Python 显示整数的素数因子的程序,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,我试图制作一个程序,将数字作为输入,并以列表格式显示该程序: # we ask for input num = int(input('enter the number of which you would like to find prime factors of\n=')) div_list = [] # we create an empty list to store all the divisors of the number prime_div = [] # we create a
# we ask for input
num = int(input('enter the number of which you would like to find prime factors of\n='))
div_list = [] # we create an empty list to store all the divisors of the number
prime_div = [] # we create a list for all the prime divisors
for _ in range(2, num-1): # we check all the divisors
if num % _ == 0:
div_list.append(_) # we add all the divisors to the list
for i in range(len(div_list)): # this loop will run the next loop for the duration of all the nums
for j in range(2, div_list[i]):
if div_list[i] % j == 0:
pass
else:
prime_div.append(div_list[i])
print('the list of all the prime factors is')
print(prime_div)
但当我运行这个程序时,它只给我一个数字的输入:
enter the number of which you would like to find prime factors of
=49
the list of all the prime factors is
[7, 7, 7, 7, 7]
我不明白为什么会这样。有什么想法吗?我认为这将解决您的问题(您在代码中使用了额外的缩进。我已在程序中注释掉):
注意:请尽量避免在python中使用
\uuu
作为变量或占位符。建议:尽量不要使用“\uu”作为变量。ok将在我的mind@RamPandey\u
通常在迭代中用作占位符,但实际值不会被使用,而只是需要循环构造(无可否认,这种情况有点罕见,但也不太罕见)当你开始使用<代码> < <代码>的值时,考虑将它重命名为更具信息性的东西,如@ ToHiguliSaleSuggest.是的,但是你能解释一下我的代码有什么问题吗?你的代码可以更优化。我没有添加复杂的代码来让你更容易。我想我可以优化它的时间复杂度。但在这种情况下,您的代码会更大。虽然您是初学者,所以我避免了这一部分。@user1055395是的,我知道,但我想让这段代码尽可能简单。
num = int(input('enter the number of which you would like to find prime factors of\n='))
div_list = [] # we create an empty list to store all the divisors of the number
prime_div = [] # we create a list for all the prime divisors
for _ in range(2, num-1): # we check all the divisors
if num % _ == 0:
div_list.append(_) # we add all the divisors to the list
for i in range(len(div_list)): # this loop will run the next loop for the duration of all the nums
for j in range(2, div_list[i]):
if div_list[i] % j == 0:
pass
else: #This line will execute if div_list[i] is a prime number. You were executing else clause again and again
prime_div.append(div_list[i]) #removed extra indentation, this was causing your error
print('the list of all the prime factors is')
print(prime_div)