猿问

如何打印出两个数字的公因数列表?

我需要打印出两个数字的公因数列表


def print_nums(x, y):

    for i in range(1, x + 1):

        if x % i == 0:

            print(i)

    for t in range(1, y + 1):

        if y % t == 0:

            print(t)



number = int(input("Enter a number: "))

number2 = int(input("Enter a second number: "))


print("Common factors are: ".format(number, number2))

print_nums(number, number2)

它打印出两个列表,但不是每个列表的公因子


眼眸繁星
浏览 190回答 3
3回答

慕田峪4524236

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  

慕的地6264312

您的代码只打印因子,而不是公因子。您可以遍历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 iprint(list(common_factors(9, 12)))  # -> [3]

Smart猫小萌

与上述解决方案基本相同的想法..但是一个漂亮的函数基本上只检查列表中非唯一的项目..就像 set 的对立面...这会返回共同因素,因为它们会出现不止一次from iteration_utilities import duplicates, unique_everseenfacs=[]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)))
随时随地看视频慕课网APP

相关分类

Python
我要回答