easy +5 pts

Modulo Remainder

Compute the remainder of a divided by b without using the modulo operator.

Write a function `modulo_remainder(a: int, b: int) -> int` that returns the remainder when `a` is divided by `b`. The function must **not** use the modulo operator `%` or the built-in `divmod`. Instead, use arithmetic operations only. The result must always have the same sign as the divisor `b` (Euclidean definition). For this problem, `b` will always be non-zero. You may assume `a` and `b` are integers (positive, negative, or zero). **Definition:** The Euclidean remainder `r` satisfies `0 <= r < abs(b)` and `a = b * q + r` for some integer `q`. For example, `modulo_remainder(-7, 3)` returns `2` because `-7 = 3 * (-3) + 2`.

Constraints

-10^9 ≤ a ≤ 10^9, -10^9 ≤ b ≤ 10^9, b ≠ 0. The function should run in O(1) time.

Example

>>> modulo_remainder(10, 3)
1
>>> modulo_remainder(-10, 3)
2
>>> modulo_remainder(10, -3)
1
>>> modulo_remainder(-10, -3)
2
>>> modulo_remainder(0, 5)
0
5 points ~5 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Start with the Python `%` result, then adjust to make it non-negative when needed.
The adjustment is `((a % b) + abs(b)) % abs(b)` but you cannot use `%` directly; think how to achieve that without modulo.
Use integer division and multiplication: `a - (a // b) * b` gives a remainder, but it may be negative when `a` and `b` have opposite signs.
After computing the truncated remainder, if it is negative, add `abs(b)`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.