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)))
添加回答
舉報