3 回答

TA贡献1875条经验 获得超5个赞
def print_nums(x, y):
zet = []
for i in range(1, x + 1):
if x % i == 0:
#print(i)
zet.append(i)
for t in range(1, y + 1):
if y % t == 0 and t in zet:
print(t)
number = int(input("Enter a number: "))
number2 = int(input("Enter a second number: "))
print("Common factors are:")
print_nums(number, number2)
运行代码示例:
Enter a number: 24
Enter a second number: 18
Common factors are:
1
2
3
6

TA贡献1817条经验 获得超6个赞
您的代码只打印因子,而不是公因子。您可以遍历xandy的公共范围并检查是否i是两者的一个因素:
def common_factors(x, y):
for i in range(2, min(x, y)+1): # 1 is trivial, so ignore it
if x % i == 0 and y % i == 0: # If x and y are both multiples of i
yield i
print(list(common_factors(9, 12))) # -> [3]

TA贡献1911条经验 获得超7个赞
与上述解决方案基本相同的想法..但是一个漂亮的函数基本上只检查列表中非唯一的项目..就像 set 的对立面...这会返回共同因素,因为它们会出现不止一次
from iteration_utilities import duplicates, unique_everseen
facs=[]
def print_nums(x, y, facs):
for i in range(1, x + 1):
if x % i == 0:
facs.append(i)
for t in range(1, y + 1):
if y % t == 0:
facs.append(t)
return list(unique_everseen(duplicates(facs)))
添加回答
举报