Modular Arithmetic in Python
Modular Arithmetic in Python
The modulo operation
Modular arithmetic focuses on the remainder left after one integer is divided by another. The modulo operation is written as amodm, where:
a is the dividend: the number being divided.
m is the modulus: the number by which the dividend is divided.
q is the quotient: the whole-number result of the division.
r is the remainder: what is left after removing q groups of size m.
These values are related by the division identity:
For a positive modulus, the remainder satisfies 0≤r<m.
For example, when 6 is divided by 2, the quotient is 3 and the remainder is 0:
When 5 is divided by 2, the quotient is 2 and the remainder is 1:
The modulo result is the remainder, not the quotient.
Modulo in Python
Python’s built-in modulo operator is %. It works with integers and floating-point numbers, though integer examples make the operation easiest to follow.
print(6 % 2) # 0
print(5 % 2) # 16 % 2is0because 2 divides 6 exactly.5 % 2is1because two groups of 2 make 4, leaving 1.
Python also provides math.fmod for modulo-like calculations. The two approaches can differ for negative values: % follows Python’s floor-division remainder convention, while fmod gives a remainder with the sign of the dividend. For ordinary nonnegative integers, both produce the expected remainder.
Constructing modulo from floor division
Python’s // operator performs floor division: it returns the floor of the quotient rather than the remainder. For example, 5//2 is 2.
The division identity can be rearranged to calculate the remainder:
Since q=a//m, the remainder can be computed as:
A Python function implementing this formula is:
def modulo(a, m):
return a - (a // m) * mHere, a is the dividend and m is the modulus. For example:
print(modulo(6, 2)) # 0
print(modulo(5, 2)) # 1For a positive modulus, this formula follows Python’s % convention, including for negative dividends, because // rounds down. The modulus must not be zero: division by zero is undefined and raises an error.
Checking the function across several values
The custom function can be compared with Python’s built-in operator over a range of integers:
for a in range(-10, 10):
for m in range(1, 10):
print(a, m, modulo(a, m) == a % m)The first range includes the integers from −10 through 9; the upper endpoint is excluded. The second range uses positive moduli, avoiding division by zero. Each comparison should be True if the custom function matches Python’s % operation.
Using modular arithmetic to wrap a clock
A 24-hour clock uses hours from 0 through 23. After hour 23, the next hour is 0, rather than 24. This wraparound is a modulo operation with modulus 24:
The offset can be positive to look forward or negative to look backward. For example:
If the current hour is 21 and the offset is 5, then (21+5)mod24=2.
If the current hour is 23 and the offset is 1, then (23+1)mod24=0.
An offset of −1 gives the previous hour, with wraparound when necessary.
In military-time notation, the hour is written from 00 to 23. A display such as 2320 means 23:20, and 0020 means 00:20.
Getting the current time with a time zone
Python’s datetime module provides date and time information. A time-zone library such as pytz can be used to obtain the current time in a specified zone. The following example adjusts the hour by an offset, wraps it using modulo 24, preserves the current minutes, and prints the result as four digits:
from datetime import datetime
import pytz
def clock(hours=0, timezone="America/New_York"):
zone = pytz.timezone(timezone)
now = datetime.now(zone)
updated_hour = (now.hour + hours) % 24
print(f"{updated_hour:02d}{now.minute:02d}")hoursis the number of hours to add or subtract. Its default value,0, displays the current hour.timezoneidentifies the desired time zone. Its default here is"America/New_York".datetime.now(zone)obtains the current time in that zone.% 24keeps the adjusted hour within the clock’s 0–23 range.The
02dformatting pads a one-digit hour or minute with a leading zero.
For example, if the current time is 23:20 and hours=1, the calculation wraps the hour to 00 while leaving the minutes unchanged, so the display is 0020. An offset of -1 displays the previous hour. A different time zone can be supplied, such as "Africa/Addis_Ababa"; available names depend on the time-zone database installed with the library.
This example adjusts only the hour. It does not add or subtract minutes, and its displayed result is a time-of-day rather than a complete date and time.
Applications of modular arithmetic
Cryptography
Modular arithmetic is used in cryptographic systems, including Diffie–Hellman key exchange. This method allows two parties to establish a shared cryptographic secret while communicating over a public channel. Modular arithmetic—especially modular exponentiation—is part of the mathematical structure that makes the exchange possible.
Check digits in product codes
Barcode numbers can include a check digit calculated from the other digits using a rule based on modular arithmetic. When a code is scanned, the check digit can be recomputed to help detect errors in the number.
UPC-A barcodes contain 12 digits, including the check digit; the checksum is based on modulo 10. A mismatch can indicate that a digit was entered or read incorrectly.
ISBNs
International Standard Book Numbers (ISBNs) also use check-digit calculations to help validate book identifiers. The calculation depends on the ISBN format: ISBN-10 uses a modulo-11 check, while ISBN-13 uses a modulo-10 check. These checks help detect many common transcription errors.
Modular arithmetic is useful whenever values must wrap around a fixed range or when a remainder-based rule is needed to validate data.

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