From 7444a1f0693c5e08d6859d549ce5485db5a988b1 Mon Sep 17 00:00:00 2001 From: Ghulam Mohiyuddin Date: Tue, 22 Oct 2019 14:56:06 +0530 Subject: [PATCH] Another method added for GCD (#1387) * Another method added for GCD * Now doctest fulfilled for added method. * Update greatest_common_divisor.py * Now unnecessary white spaces removed. * Cycle_Detection_Undirected_Graph Cycle_Detection_Undirected_Graph using Disjoint set DataStructure * Update greatest_common_divisor.py again * Again Updated cycle_detection_undirected_graph.py * Delete cycle_detection_undirected_graph.py * Add doctests and format the code with psf/black * fixup: Typo * Update greatest_common_divisor.py * greatest_common_divisor() --- maths/greatest_common_divisor.py | 38 ++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 7 deletions(-) diff --git a/maths/greatest_common_divisor.py b/maths/greatest_common_divisor.py index ebc08f37f..a1b915bc3 100644 --- a/maths/greatest_common_divisor.py +++ b/maths/greatest_common_divisor.py @@ -5,20 +5,44 @@ Wikipedia reference: https://en.wikipedia.org/wiki/Greatest_common_divisor """ -def gcd(a, b): - """Calculate Greatest Common Divisor (GCD).""" - return b if a == 0 else gcd(b % a, a) +def greatest_common_divisor(a, b): + """ + Calculate Greatest Common Divisor (GCD). + >>> greatest_common_divisor(24, 40) + 8 + """ + 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 def main(): - """Call GCD Function.""" + """Call Greatest Common Divisor function.""" try: - nums = input("Enter two Integers separated by comma (,): ").split(",") + nums = input("Enter two integers separated by comma (,): ").split(",") num_1 = int(nums[0]) num_2 = int(nums[1]) - print(f"gcd({num_1}, {num_2}) = {gcd(num_1, num_2)}") + print(f"greatest_common_divisor({num_1}, {num_2}) = {greatest_common_divisor(num_1, num_2)}") + print(f"By iterative gcd({num_1}, {num_2}) = {gcd_by_iterative(num_1, num_2)}") except (IndexError, UnboundLocalError, ValueError): - print("Wrong Input") + print("Wrong input") if __name__ == "__main__":