Skip to content

Commit 9d7733f

Browse files
Fix ZeroDivisionError on zero operands in least_common_multiple
least_common_multiple_slow raised ZeroDivisionError for a zero operand (0 % n in the loop guard), e.g. least_common_multiple_slow(0, 5), and least_common_multiple_fast raised it for (0, 0) via floor-division by gcd(0, 0) == 0. The least common multiple is 0 whenever an operand is 0 (consistent with math.lcm), so both functions return 0 in that case. Adds doctests covering the zero inputs.
1 parent e3b01ec commit 9d7733f

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

maths/least_common_multiple.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,15 @@ def least_common_multiple_slow(first_num: int, second_num: int) -> int:
1414
10
1515
>>> least_common_multiple_slow(12, 76)
1616
228
17+
>>> least_common_multiple_slow(0, 5)
18+
0
19+
>>> least_common_multiple_slow(5, 0)
20+
0
21+
>>> least_common_multiple_slow(0, 0)
22+
0
1723
"""
24+
if first_num == 0 or second_num == 0:
25+
return 0
1826
max_num = first_num if first_num >= second_num else second_num
1927
common_mult = max_num
2028
while (common_mult % first_num > 0) or (common_mult % second_num > 0):
@@ -30,7 +38,15 @@ def least_common_multiple_fast(first_num: int, second_num: int) -> int:
3038
10
3139
>>> least_common_multiple_fast(12,76)
3240
228
41+
>>> least_common_multiple_fast(0, 5)
42+
0
43+
>>> least_common_multiple_fast(5, 0)
44+
0
45+
>>> least_common_multiple_fast(0, 0)
46+
0
3347
"""
48+
if first_num == 0 or second_num == 0:
49+
return 0
3450
return first_num // greatest_common_divisor(first_num, second_num) * second_num
3551

3652

0 commit comments

Comments
 (0)