Modular Arithmetic in Python


Modular Arithmetic in Python

Michael
Welcome! Today we’re exploring modular arithmetic and how to use it in Python. The central idea is simple: divide one number by another, then focus on the remainder.

Anna
So if I see “a modulo b,” I should think: divide a by b and ask what’s left over. And b is called the modulus—it sets the size of the remainder range when we’re working with positive whole numbers.

Michael
Exactly. In the division relationship, a is the dividend, b is the divisor, q is the quotient—the number of whole times b fits into a—and the remainder is what’s left. For example, six divided by two has a quotient of three and a remainder of zero.

Anna
And five divided by two has a quotient of two, because two fits into five twice. That uses four, leaving a remainder of one, so five modulo two equals one.

Michael
In Python, the percent sign performs this operation: `a % b`. It works with integers and floating-point numbers, though we’ll focus on integers here. Python also offers other tools, such as `math.fmod`, but different functions can behave differently, so it’s worth checking their documentation when that distinction matters.

Anna
Let’s verify those examples directly: `6 % 2` evaluates to zero, and `5 % 2` evaluates to one. That matches the division-and-remainder explanation.

Michael
Right. A useful habit is to check the quotient and remainder together. Six is two times three, with nothing left over; five is two times two, with one left over. If the divisor doesn’t fit evenly, the modulo result captures that leftover.

Anna
Can we build the same operation ourselves, rather than relying on the percent sign?

Michael
Yes. Python’s floor-division operator, `//`, gives the floor quotient. For ordinary positive integers, the remainder can be calculated as `a - (a // b) * b`. In code, a function could be written as `def modulo(a, b): return a - (a // b) * b`, where `a` is the number being divided and `b` is the modulus.

Anna
Let’s use five and two. Floor division gives `5 // 2`, which is two. Multiply that quotient by two to get four, then subtract four from five. The result is one—the same remainder as `5 % 2`.

Michael
And for six and two, floor division gives three. Two times three is six, and six minus six is zero. So the formula reproduces both examples.

Anna
You can test the custom function against Python’s built-in modulo operator over many integer pairs. For example, loop over values from negative ten up to, but not including, ten, and compare `modulo(a, b)` with `a % b` for nonzero values of `b`.

Michael
That comparison is a practical check that the implementation agrees with Python. Negative values are a good reason to test rather than assume: Python’s `//` is floor division, and its modulo results follow Python’s division convention. The formula using `//` matches that convention when the modulus isn’t zero.

Anna
Now let’s see why modulo is handy beyond small arithmetic examples: we can use it to make a clock wrap around. We’ll represent hours in 24-hour, or military, time, from 00 through 23. After 23 comes 00 again—not 24.

Michael
The wraparound rule is exactly what modulo 24 gives us. If the current hour is 21 and we move forward five hours, we calculate `(21 + 5) % 24`, which is two. In military-style formatting, that hour is 02, rather than 26.

Anna
And we can move backward, too. Add a negative offset: from 02, adding negative three hours gives `(2 - 3) % 24`, which is 23 in Python. The clock wraps back to the previous day’s final hour.

Michael
For a Python clock function, we can use `datetime` to get the current time and `pytz` to select a time zone. The function can accept an hour offset, defaulting to zero, and a time-zone name, such as `America/New_York`. It reads the current hour and minute in that zone, then calculates the updated hour with `(current_hour + offset) % 24`.

Anna
The minutes can stay unchanged if the function is only shifting by whole hours. So if the current time is 23:20 and we add one hour, the result is 00:20. We’ve wrapped the hour around, but we haven’t added any minutes.

Michael
To display the result consistently, convert the hour and minute values to strings and pad a one-digit value with a leading zero. That gives formats such as 03:09 rather than 3:9. You can combine the padded values into a military-time display like 0309.

Anna
The function can print the formatted time, or it could return it if another part of a program needs to use the result. And because it accepts a time-zone parameter, the same approach can display the current local hour for a different location, provided you use a valid time-zone name from the time-zone database.

Michael
A quick note on the clock’s scope: this approach is changing the hour while retaining the current minute. It’s a teaching example of modulo-based wraparound, not a complete scheduling system. The important arithmetic is still the same—add an offset, then take the result modulo 24.

Anna
That wraparound pattern appears in plenty of real systems. In cryptography, modular arithmetic is used in methods such as the Diffie–Hellman key exchange, which lets two parties securely exchange cryptographic keys over a public channel.

Michael
It also helps validate identification numbers. UPC barcodes include a checksum that uses modular arithmetic to help verify whether a code is valid. ISBNs, the standard numbers used to identify books, also use modular arithmetic in their validation rules.

Anna
So the same idea connects a tiny Python expression to clocks, cryptography, and checking codes. When you see a modulo operation, ask what is wrapping around or what remainder is being used to validate something.

Michael
And when you implement it, test a few hand-worked cases first, then compare your function against Python’s `%` operator across a range of inputs. That makes the quotient-and-remainder idea concrete and helps catch mistakes.

Anna
That’s modular arithmetic: divide, keep the remainder, and use that remainder to create useful patterns—especially when values need to cycle back to the beginning.

Ask anything
We've read this whole study set, so questions about it get the best answers.