Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 7 additions & 6 deletions gcd.py
Original file line number Diff line number Diff line change
@@ -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
14 changes: 14 additions & 0 deletions gcd_fixed.py
Original file line number Diff line number Diff line change
@@ -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))