找出数字的素因子 - 输出错误

时间:2017-10-06 14:43:03

标签: python-2.7

代码如下:

n = input("Enter n: ")
f = 0
j = 2
for i in range(1, n/2 + 1):
  if n % i == 0:
    if i % j == 0:
      f = 1
      break
    if f ==0:
      print i ,
    j = j + 1

当我输入21作为输入时,我只得到1.

任何人都可以更正我的代码吗?

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

n = input("Enter n: ")
f = 0
j = 2
for i in range(1,n/2+1):
  if n%i == 0:
    for j in range(2,i/2+1):   #you need another loop to insure i has no factors
      if i%j == 0:
        f+=1

    if f==0:
      print i ,
  f = 0