程序显示整数的素数因子

时间:2018-06-09 08:56:23

标签: 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 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)

但是当我运行这个程序时,它只输入1个数字:

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]

我不明白为什么会这样。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我认为这将解决您的问题(您在代码中使用了额外的缩进。我已在程序中注释掉了):

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)

注意:请尽量避免在python中使用_作为变量或占位符。