diff --git a/gcd.py b/gcd.py index 5880a5b..86a166e 100644 --- a/gcd.py +++ b/gcd.py @@ -1,17 +1,18 @@ # Wrong gcd find 5 mistakes -def gcd(a, b): - assert a <= 0 and b >= 0 +def gcd(a, b): # mistake 1 - we do not specify explicitly that the type must be int + assert a <= 0 and b >= 0 # mistake 2 - a will be asserted to be *less* than 0 in this case; + # mistake 3 - there is no error message in case assertion fails - it is optional, but still better to have it while a and b: if a > b: - a = a / b + a = a / b # mistake 4 - we have to use modulo in order to know both the remainder and to escape the loop once the remainder would be 0 else: - b = b / a - return min(a, b) + b = b / a # same mistake 4 + return min(a, b) # mistake 5 - should be max, as we are looking for the *greatest* divisor # Examples # gcd(10, 0) => 10 # gcd(123, 3) => 3 # gcd(1000000, 64) => 64 -# gcd(0, 0) => 0 +# gcd(0, 0) => 0 \ No newline at end of file diff --git a/gcd_fixed.py b/gcd_fixed.py new file mode 100644 index 0000000..69f9120 --- /dev/null +++ b/gcd_fixed.py @@ -0,0 +1,14 @@ +def gcd(a:int, b:int): + assert a >= 0 and b >= 0, "Please do not use negative integers" + while a and b: + if a > b: + a = a % b + else: + b = b % a + return max(a, b) + +print(gcd(10, 0)) +print(gcd(123, 3)) +print(gcd(1000000, 64)) +print(gcd(0, 0)) +print(gcd(32, 64)) \ No newline at end of file