A, two number of greatest common divisor
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)
At first, the above code is never understood, why it is just 6, because according to Visual, 1, 2, 3, 6 are in accordance with the if conditions, should be printed out.
I learned that because there is no distinction between code groups, the location of print () determines which m value it will eventually print out.
Differentiate the output of the code (take Common_divisor (12, 18) as an example):
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)
For 1, the print () statement is executed only when the IF condition is satisfied, and for 2, the print () is executed once for the For loop, and finally, for the first code, (is not a bit of an exhaustive meaning ...). ), find all the M values that meet the criteria, then print out the last one, and execute only once!!
1.
>>> common_divisor 1The Common divisor is 12The common divisor are 23The common divisor is 36The common div Isor is 6
2.
>>> common_divisor 1The Common divisor is 12The common divisor are 23The common divisor is 3The common divi SOR is 3The common divisor is 36The common divisor are 6The common divisor is 6The common divisor are 6The common divisor is 6The Common divisor is 6The common divisor are 6The common divisor is 6
b, the least common multiple of two numbers:
def common_mutiple (I, j): Maxnum = max (i, J) while true:if maxnum% i = = 0 and maxnum% J ==0:PR Int ("The Common mutiple is%d"%maxnum) # #列举, will encounter the first maxnum that satisfies the IF condition print out, then break, jump out while loop. Break Else:maxnum = Maxnum + 1
Python core Programming Chapter fifth Practice -5.11-Greatest common divisor and least common multiple