首页 > 代码库 > python核心编程第五章练习-5.11-最大公约数和最小公倍数

python核心编程第五章练习-5.11-最大公约数和最小公倍数

a、求两个数的最大公约数 

def common_divisor(a, b):

    for i in range(1, min(a, b) + 1):
        if a % i == 0 and b % i ==0:
            m = i
    print ("The common divisor is %d" %m)

 

一开始对上面这段代码始终没理解,为什么得到是就仅仅是6,因为按照目测,1, 2, 3, 6均符合if的条件,应该都会打印出来。

讨教之后才知道是因为没有区分代码组,print()的位置决定了它最终打印出哪一个m值。

区分一下代码的输出(以common_divisor(12, 18)为例):

 1、

def common_divisor(a, b):
    for i in range(1, min(a, b) + 1):
        if a % i == 0 and b % i ==0:
            m = i

            print(i) 

            print ("The common divisor is %d" %m)

2、 

def common_divisor(a, b):
    for i in range(1, min(a, b) + 1):
        if a % i == 0 and b % i ==0:
            m = i

    print(i) 

        print ("The common divisor is %d" %m)

 

 对于1,只有if条件满足的时候,就执行print()语句;而对于2,每执行一次for循环,就执行一次print();最后,对于开头的代码,(是不是有点穷举的意思。。。),找到所有满足条件的m值,然后打印出最后一个,且只执行一次!!

1、

>>> common_divisor(12, 18)
1
The common divisor is 1
2
The common divisor is 2
3
The common divisor is 3
6
The common divisor is 6

 2、

>>> common_divisor(12, 18)
1
The common divisor is 1
2
The common divisor is 2
3
The common divisor is 3
The common divisor is 3
The common divisor is 3
6
The common divisor is 6
The common divisor is 6
The common divisor is 6
The common divisor is 6
The common divisor is 6
The common divisor is 6
The common divisor is 6

 

 

b、求两个数的最小公倍数:

def common_mutiple(i, j):
    maxnum = max(i, j)
    while True:
        if maxnum % i == 0 and maxnum % j ==0:
            print ("The common mutiple is %d" %maxnum) ##列举,将遇到的第一个满足if条件的maxnum打印出来,然后break,跳出while循环。
            break
        else:
            maxnum = maxnum + 1

 

 

 

 

 

 

 

python核心编程第五章练习-5.11-最大公约数和最小公倍数