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

标签 python python-3.x list for-loop

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

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)

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

最佳答案

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  

关于python - 如何打印两个数字的公因数列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57780560/

相关文章:

python - 如何让用户在kivy中选择文件作为背景图片?

python - 将特定单元格定义为 pandas 数据框中的变量

python - 如何在Python中处理这个JSON文件?

python - Tensorflow 在 Mac 上无法从 Anaconda 运行

python-3.x - Telethon 中有没有办法从聊天中获取消息以及发件人姓名、日期和时间?

python - Django 1.4.1 'settings.DATABASES improperly configured' 错误

python - Keras开关功能错误

Python Pandas DataFrame JSON 转换器列表错误

python - 如何将相似列表转换为列表?

java - 在 grails 中减去具有重复元素的列表