Fix ZeroDivisionError on zero operands in least_common_multiple#14845
Fix ZeroDivisionError on zero operands in least_common_multiple#14845CharlesCNorton wants to merge 2 commits into
Conversation
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.
zain-cs
left a comment
There was a problem hiding this comment.
Good fix! The zero-check guard correctly handles all zero operand cases and matches the behavior of math.lcm. Doctests for the zero cases are well added.
One minor suggestion: consider adding the zero cases to TestLeastCommonMultiple.test_inputs as well, so the unit test class is as comprehensive as the doctests.
Otherwise looks clean and solid! 👍
|
@zain-cs Thanks, good call. Added the three zero cases to |
zain-cs
left a comment
There was a problem hiding this comment.
Thanks for addressing the suggestion — the zero cases are now added to test_inputs and expected_results in TestLeastCommonMultiple, and both _slow and _fast are exercised on them. This is now consistent with the doctests. Approved! ✅
Describe your change:
least_common_multiple_slowandleast_common_multiple_fastraiseZeroDivisionErrorwhen either operand is0:least_common_multiple_slow(0, 5),least_common_multiple_slow(5, 0), andleast_common_multiple_slow(0, 0)divide by zero in thecommon_mult % first_num/common_mult % second_numloop guard.least_common_multiple_fast(0, 0)divides bygreatest_common_divisor(0, 0) == 0.The least common multiple is
0whenever an operand is0, which matches the standard library (math.lcm(0, 5) == 0,math.lcm(0, 0) == 0). Both functions now return0in that case before the division, so they agree withmath.lcmand with each other. Behavior for non-zero inputs is unchanged. Doctests for the zero cases are added.Checklist: