Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Reduce Binary GCD algorithm solution in Clear category for The Greatest Common Divisor by r.bathoorn
from functools import reduce
def gcd(a,b):
d = 0
while a % 2 == 0 and b % 2 == 0:
a = a/2
b = b/2
d = d + 1
while a != b:
if a % 2 == 0:
a = a/2
else:
if b % 2 == 0:
b = b/2
else:
if a > b:
a = (a - b)/2
else:
b = (b - a)/2
return a*(2**d)
def greatest_common_divisor(*args):
"""
Find the greatest common divisor
"""
return reduce(gcd,args)
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert greatest_common_divisor(6, 4) == 2, "Simple"
assert greatest_common_divisor(2, 4, 8) == 2, "Three arguments"
assert greatest_common_divisor(2, 3, 5, 7, 11) == 1, "Prime numbers"
assert greatest_common_divisor(3, 9, 3, 9) == 3, "Repeating arguments"
March 27, 2020
Comments: