Division algorithm
A division algorithm is an algorithm that computes the quotient and remainder of two integers. Its success is guaranteed by the following theorem:
In other words, any integer \(n\) can be uniquely expressed as a linear combination of some quotient \(q\) and remainder \(r\), for every given positive divisor \(d.\) Likewise, if you isolate the remainder \(r\), it becomes a linear combination of \(n\) and \(d.\) The Euclidean algorithm is based on this fact.
Anyway, let's look at a specific division algorithm that will describe exactly how \(q = n \text{ div } d\) and \(r = n \bmod d\) are computed. It takes the form of repeated subtraction and depends on the sign of the dividend:
algorithm division is
input: two integers, n and d, where d > 0
output: two integers, q = n div d and r = n mod d
q ← 0
r ← n
if n ≥ 0 (the non-negative case)
while r ≥ d
q ← q + 1
r ← r - d
else (the negative case)
while r < 0
q ← q - 1
r ← r + d
So, if you ever find yourself confused on how to compute \(\bmod\), no worries. You can trust that this algorithm will always be correct.