2019-07-10 20:09:24 +00:00
|
|
|
"""
|
2019-10-14 18:35:51 +00:00
|
|
|
Greatest Common Divisor.
|
2019-07-10 20:09:24 +00:00
|
|
|
|
|
|
|
Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
2019-10-22 09:26:06 +00:00
|
|
|
def greatest_common_divisor(a, b):
|
|
|
|
"""
|
|
|
|
Calculate Greatest Common Divisor (GCD).
|
|
|
|
>>> greatest_common_divisor(24, 40)
|
|
|
|
8
|
2019-10-29 10:06:37 +00:00
|
|
|
>>> greatest_common_divisor(1, 1)
|
|
|
|
1
|
|
|
|
>>> greatest_common_divisor(1, 800)
|
|
|
|
1
|
|
|
|
>>> greatest_common_divisor(11, 37)
|
|
|
|
1
|
|
|
|
>>> greatest_common_divisor(3, 5)
|
|
|
|
1
|
|
|
|
>>> greatest_common_divisor(16, 4)
|
|
|
|
4
|
2019-10-22 09:26:06 +00:00
|
|
|
"""
|
|
|
|
return b if a == 0 else greatest_common_divisor(b % a, a)
|
|
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
Below method is more memory efficient because it does not use the stack (chunk of memory).
|
|
|
|
While above method is good, uses more memory for huge numbers because of the recursive calls
|
|
|
|
required to calculate the greatest common divisor.
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
def gcd_by_iterative(x, y):
|
|
|
|
"""
|
|
|
|
>>> gcd_by_iterative(24, 40)
|
|
|
|
8
|
|
|
|
>>> greatest_common_divisor(24, 40) == gcd_by_iterative(24, 40)
|
|
|
|
True
|
|
|
|
"""
|
|
|
|
while y: # --> when y=0 then loop will terminate and return x as final GCD.
|
|
|
|
x, y = y, x % y
|
|
|
|
return x
|
2018-10-19 12:48:28 +00:00
|
|
|
|
2019-07-10 20:09:24 +00:00
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
def main():
|
2019-10-22 09:26:06 +00:00
|
|
|
"""Call Greatest Common Divisor function."""
|
2018-10-19 12:48:28 +00:00
|
|
|
try:
|
2019-10-22 09:26:06 +00:00
|
|
|
nums = input("Enter two integers separated by comma (,): ").split(",")
|
2019-07-10 20:09:24 +00:00
|
|
|
num_1 = int(nums[0])
|
|
|
|
num_2 = int(nums[1])
|
2019-10-22 17:13:48 +00:00
|
|
|
print(
|
|
|
|
f"greatest_common_divisor({num_1}, {num_2}) = {greatest_common_divisor(num_1, num_2)}"
|
|
|
|
)
|
2019-10-22 09:26:06 +00:00
|
|
|
print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}")
|
2018-10-19 12:48:28 +00:00
|
|
|
except (IndexError, UnboundLocalError, ValueError):
|
2019-10-22 09:26:06 +00:00
|
|
|
print("Wrong input")
|
2019-07-10 20:09:24 +00:00
|
|
|
|
2018-10-19 12:48:28 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2018-10-19 12:48:28 +00:00
|
|
|
main()
|