1. Home
  2. Explore
  3. Computer Science
  4. Modular Arithmetic in Python

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

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 a mod ma \bmod mamodm, where:

  • aaa is the dividend: the number being divided.

  • mmm is the modulus: the number by which the dividend is divided.

  • qqq is the quotient: the whole-number result of the division.

  • rrr is the remainder: what is left after removing qqq groups of size mmm.

These values are related by the division identity:

a=mq+ra = mq + ra=mq+r

For a positive modulus, the remainder satisfies 0≤r<m0 \le r < m0≤r<m.

For example, when 666 is divided by 222, the quotient is 333 and the remainder is 000:

6=2⋅3+06 = 2 \cdot 3 + 06=2⋅3+0

When 555 is divided by 222, the quotient is 222 and the remainder is 111:

5=2⋅2+15 = 2 \cdot 2 + 15=2⋅2+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)  # 1
  • 6 % 2 is 0 because 222 divides 666 exactly.

  • 5 % 2 is 1 because two groups of 222 make 444, leaving 111.

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//25 // 25//2 is 222.

The division identity can be rearranged to calculate the remainder:

r=a−mqr = a - mqr=a−mq

Since q=a//mq = a // mq=a//m, the remainder can be computed as:

r=a−(a//m)mr = a - (a // m)mr=a−(a//m)m

A Python function implementing this formula is:

def modulo(a, m):
    return a - (a // m) * m

Here, a is the dividend and m is the modulus. For example:

print(modulo(6, 2))  # 0
print(modulo(5, 2))  # 1

For 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-10−10 through 999; 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 000 through 232323. After hour 232323, the next hour is 000, rather than 242424. This wraparound is a modulo operation with modulus 242424:

new hour=(current hour+offset) mod 24\text{new hour} = (\text{current hour} + \text{offset}) \bmod 24new hour=(current hour+offset)mod24

The offset can be positive to look forward or negative to look backward. For example:

  • If the current hour is 212121 and the offset is 555, then (21+5) mod 24=2(21 + 5) \bmod 24 = 2(21+5)mod24=2.

  • If the current hour is 232323 and the offset is 111, then (23+1) mod 24=0(23 + 1) \bmod 24 = 0(23+1)mod24=0.

  • An offset of −1-1−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 242424, 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}")
  • hours is the number of hours to add or subtract. Its default value, 0, displays the current hour.

  • timezone identifies the desired time zone. Its default here is "America/New_York".

  • datetime.now(zone) obtains the current time in that zone.

  • % 24 keeps the adjusted hour within the clock’s 000–232323 range.

  • The 02d formatting 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 101010. 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-111111 check, while ISBN-13 uses a modulo-101010 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.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent