+ 1
how to code for g.c.d of 2 numbers? like g.c.d of 12 and 67 is 1
2 Answers
+ 3
GCD formula can be calculated directly by using the fractions standard library.
>>> from fractions import gcd
>>> a = gcd(12,67)
>>> print(a)
+ 2
well, start with what you know:
we want to find the greatest common denominator between two numbers:
def gcd(a, b):
print(gcd(12, 67))
next, we want to find out how exactly a gcd is calculated - using Euclids algorithm.
def gcd(a, b):
while a != 0:
a, b = b%a, a
return b
# We replace the larger of the two numbers by its remainder when divided by the smaller of the two and stop when the remainder reaches 0 (while a != 0: replace b with the remainder of the two numbers (b%a) when you divide them)
print(gcd(12, 67))