首页 > 其他分享 >common divisor---求最大公约数

common divisor---求最大公约数

时间:2022-10-13 22:09:42浏览次数:57  
标签:divisor --- second GCD common input first

  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
  2. .
Swap. If

then swap

p

and

q

,

.

Subtract. If

then subtract

q

from

p

,

.

  1. 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))







标签:divisor,---,second,GCD,common,input,first
From: https://blog.51cto.com/u_15797945/5754703

相关文章