1. 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, p and q

    Loop. Loop until p = q.

    Swap. If p < q then swap p and q, p \leftrightarrows q.

    Subtract. If p > q then subtract q from p, p \gets p - q.

    Result. Print p

# -*- coding: UTF-8 -*-

a = input("a = ")
b = input("b = ")
if a > b :
    a, b = b, a
for i in range(1,a+1):
    if a % i == 0 and b % i == 0 :
        q = i
        continue
print "the common divisor is ", q
    
>>> ================================ RESTART ================================
>>> 
a = 4
b = 12
the common divisor is  4
>>> ================================ RESTART ================================
>>> 
a = 6
b = 9
the common divisor is  3
>>> ================================ RESTART ================================
>>> 
a = 8
b = 4
the common divisor is  4
>>> 

另一种解法:

辗转相除法,假设用f(x, y)表示x,y的最大公约数,取k = x/y,b = x%y,则x = ky + b,如果一个数能够同时整除x和y,则必能同时整除b和y;而能够同时整除b和y的数也必能同时整除x和y,即x和y的公约数与b和y的公约数是相同的,其最大公约数也是相同的,则有f(x, y)= f(y, x%y)(y > 0),如此便可把原问题转化为求两个更小数的最大公约数,直到其中一个数为0,剩下的另外一个数就是两者最大的公约数。

# -*- 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 a
print "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, first
	while second != 0:
		first, second = second, first % second
	return first

first = 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))






posted on 2022-07-05 18:12  我在全球村  阅读(55)  评论(0编辑  收藏  举报