easy +8 pts

Integer division and remainder

Implement a function that returns the quotient and remainder of integer division.

Write a function `divide_with_remainder(dividend, divisor)` that takes two integers (`dividend` and `divisor`) and returns a tuple `(quotient, remainder)` such that `dividend == divisor * quotient + remainder` and `0 <= remainder < abs(divisor)`. The quotient is the integer result of the division (truncated toward zero, as in Python's `//` operator). The function should raise a `ZeroDivisionError` if the divisor is zero. Ensure that the remainder has the same sign as the divisor? Actually, the requirement is `0 <= remainder < abs(divisor)`, so remainder is non-negative. But that is inconsistent with Python's `%` for negative divisor. To avoid confusion, we'll define: remainder must satisfy `dividend = divisor * quotient + remainder` and `0 <= remainder < abs(divisor)`. The quotient is the largest integer such that `divisor * quotient <= dividend` if divisor is positive, or the smallest integer such that `divisor * quotient >= dividend` if divisor is negative? That is messy. Let's simplify: The problem is to implement Euclidean division: quotient and remainder such that `dividend = divisor * quotient + remainder` and `0 <= remainder < abs(divisor)`. This is the standard mathematical definition. Note that this differs from Python's `//` and `%` when divisor is negative. For example, `divmod(-7, 3)` gives `(-3, 2)` because -3*3+2=-7 and 0<=2<3. But Python's `//` gives -3 and `%` gives 2, so it matches for positive divisor. For negative divisor, e.g., `divmod(7, -3)` in Euclidean gives quotient -2 and remainder 1 because -2*(-3)+1=7. Python's `//` gives -3 and `%` gives -2 because -3*(-3)+(-2)=7. So we need to implement Euclidean division. Implement the function accordingly. Use only basic operators.

Constraints

`dividend` and `divisor` are integers. `divisor` may be negative. If `divisor == 0`, raise `ZeroDivisionError`. The absolute value of inputs can be up to 10^9. Complexity should be O(1).

Example

>>> divide_with_remainder(17, 5)
(3, 2)
>>> divide_with_remainder(-17, 5)
(-4, 3)
>>> divide_with_remainder(17, -5)
(-3, 2)
>>> divide_with_remainder(-17, -5)
(4, 3)
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Remember Euclidean division: remainder must be non-negative and less than absolute value of divisor.
Use `abs(divisor)` and the `%` operator to compute remainder, then adjust.
If `divisor` is negative, Python's `%` gives a negative remainder; add `abs(divisor)` to make it non-negative and adjust quotient accordingly.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.