Basics 0/129

Numbers and arithmetic · 1 of 4 Advanced

Integer division and digits

Use the quotient and remainder to read the digits of a number, write it in another base, and convert spreadsheet column labels, with the one place where Python and C++ disagree.

2,576 words · 12 min read

Part 1 of 6 Quotient and remainder

Take a number apart with division

A program stores 4096 as one value. The digits 4, 0, 9 and 6 are not kept anywhere, yet many problems are about digits: whether a number reads the same backwards, what its digits add up to, how it is written in binary. In this lesson we take numbers apart with one tool, division with a remainder. Later lessons use the same tool to find common divisors, to test whether a number is prime and to show that a sequence of remainders has to repeat.

Dividing 17 by 5 gives two results. The quotient is 3, the number of whole fives that fit into 17, and the remainder is 2, what is left over:

17=3⏟quotient×5+2⏟remainder17 = \underbrace{3}_{\text{quotient}} \times 5 + \underbrace{2}_{\text{remainder}}

In Python the quotient is 17 // 5 and the remainder is 17 % 5. A single / is a different operator: 17 / 5 is the floating-point number 3.4.

Sign up to run
items = 17
group_size = 5
print(items // group_size)
print(items % group_size)

Prints 3, then 2.

Definition

For integers a≥0a \ge 0 and b>0b > 0, dividing aa by bb gives exactly one pair of integers qq and rr with a=q×b+ra = q \times b + r and 0≤r<b0 \le r < b. The quotient is qq and the remainder is rr.

The remainder is always smaller than the number we divide by, so dividing by 5 can only leave 0, 1, 2, 3 or 4. A remainder of 5 or more would mean that another five still fits.

When the remainder is 0, we say that bb divides aa. Then bb is a divisor of aa, also called a factor, and aa is a multiple of bb. In code the test is a % b == 0: 12 % 3 is 0, so 3 divides 12, and 12 % 5 is 2, so 5 does not divide 12.

Dividing by 0 has no quotient and no remainder. Python raises ZeroDivisionError for both // and %.