Greatest Common Divisor. The greatest common divisor is thelargest number which will evenly divide two other numbers. examples: gcd (5, 10) = 5, the largest number that evenly divides 5 and 10.gcd( 21, 28) = 7, the largest
Number that divides 21 and 28.
GCD's are used to reduce fractions. Once you have The GCD of thenumerator and denominator, they can both be divided by the GCD toreduce the fraction to simplest form. 21/28 reduces to 3/4.
Greatest common divisor of two integers,
PAndQ
Loop. Loop.
Swap. If then swap
PAndQ,.
Subtract. If then subtract
QFromP,.
Result. PrintP
# -*- coding: UTF-8 -*-a = input("a = ")b = input("b = ")if a > b : a, b = b, afor i in range(1,a+1): if a % i == 0 and b % i == 0 : q = i continueprint "the common divisor is ", q
>>> ================================ RESTART ================================>>> a = 4b = 12the common divisor is 4>>> ================================ RESTART ================================>>> a = 6b = 9the common divisor is 3>>> ================================ RESTART ================================>>> a = 8b = 4the common divisor is 4>>>
Another solution:
Assume that f (x, y) is used to represent the maximum common divisor of X and Y. If K is x/y and B is X % Y, x = Ky + B, if a number can divide X and Y at the same time, it must be able to divide B and Y at the same time, and the number that can divide B and Y at the same time must be able to divide X and Y at the same time, that is to say, the common divisor of X and Y is the same as that of B and Y, and the maximum common divisor is the same, then f (x, y) = f (y, X % Y) (Y> 0), so that the original problem can be converted to calculate the maximum number of the two decimal places, until one of them is 0, and the other number is the maximum number of the two.
# -*- coding: UTF-8 -*-a = input("a = ")b = input("b = ")def gcd(a,b): if a < b : a, b = b, a while b != 0: a, b = b, a % b return aprint "the common divisor is ", gcd(a,b)
#!/usr/bin/env python'gcd.py -- calculate the greatest common divisor'def gcd(first, second):if (first < second):first, second = second, firstwhile second != 0:first, second = second, first % secondreturn firstfirst = int(raw_input('Please enter the first number: '))second = int(raw_input('Please enter the second number: '))print "the greatest common divisor of %d and %d is %d" \% (first, second, gcd(first, second))