AlgoTales · Roadmap

Modular arithmetic

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Modular arithmetic is clock maths: numbers wrap back to the start after reaching a limit, and you keep only the remainder. It is how you turn any big number into a small slot, spread work evenly, or keep values in a fixed range.

Practical use cases

  • Web app: Spreading users across servers. A site has 5 servers and wants each user to always land on the same one. Taking the user id and keeping the remainder after dividing by 5 gives a number from 0 to 4, and that is the server. Traffic spreads evenly, and no lookup table is needed.
  • Web app: Image carousel that wraps around. A homepage slider with 6 banners must go from the last banner back to the first when the user clicks next. Instead of an if-statement, the next index is the current index plus one, keeping the remainder when divided by 6. It works for clicking forward or, with a small tweak, backward.
  • System: Hash tables and circular buffers. A hash table turns a huge hash number into a bucket position with a remainder, and a circular log buffer uses it to wrap back to the start when it is full. Both rely on a remainder to fit any number into a fixed set of slots.

The story: The Weekday Wheel

Mira's exam was exactly 17 days away, and she wanted to know which day of the week it fell on. Today was Sunday. "Do I count seventeen days on my fingers?" she moaned. Grandpa Bhaskar pointed to the wall calendar. "The week is a wheel. After every 7 days it comes back to where it started."

"So walk one lap (7 days), you are on Sunday. Another lap (14 days), Sunday again. You used 14 of your 17 days. Only 3 days remain, so the exam is on Wednesday." Mira clapped. "The laps do not matter, only the leftover!"

That leftover is called the remainder, and working with remainders is called modular arithmetic (or "clock arithmetic"). It is what a clock does: 10 o'clock plus 5 hours is 3 o'clock, because after 12 it starts over. It is also what happens when you share 17 sweets among 5 kids: each gets 3, and 2 are left over.

Grandpa added a secret: "You can take the remainder at any point and the answer stays right." Big sums can be kept small by reducing after every step. Computers love this, because it keeps numbers from growing too large.

How to spot this problem, and where you need it

You need numbers to wrap around, repeat in a cycle, or be sorted into a fixed number of groups, and your code is full of if-statements checking whether a value passed the limit.

Signs you need it

  • A value must return to zero or one after hitting a maximum, like days of the week, seats in a row or carousel slides.
  • You are assigning items to one of N groups, shards, servers or buckets as evenly as possible.
  • The problem statement says return the answer modulo a big number, or asks which day it will be after N days.

Where to use it in a project

  • Load balancing and sharding: choosing a server, database or cache node from a user id.
  • Scheduling and calendars: repeating tasks every N days, rotating on-call duty, picking the next slide.

The solution

Decide the size of the cycle, say 7 for weekdays. To place any number in the cycle, divide it by the size and keep only the remainder: that is the position from zero up to the size minus one. To move forward, add and take the remainder again. To avoid huge numbers, reduce the remainder after each step instead of at the end.

Payoff: Before: a tangle of if-statements for every wrap-around. After: one remainder operation sends 10 million users evenly over 5 servers.

Explain it like I am 8

Imagine a clock with only 7 hours. Walk around it and every time you pass the top you start counting again. After 17 steps, where do you stand? Just ignore the full laps and count the few steps left over.

How it works, step by step

  1. Pick the size of the wheel (the modulus), like 7 days or 12 hours.
  2. Take any number and ask: after removing as many full laps as possible, what is left? That is a % m.
  3. Add or multiply first, reduce later or reduce as you go: (a + b) % m equals ((a % m) + (b % m)) % m.
  4. Careful with negatives: in PHP and JS, -1 % 7 gives -1. Fix it with ((a % m) + m) % m.
  5. Remember the range: the result is always between 0 and m-1.

The code in four languages

PHP

<?php
$DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

// Which weekday is it, 'later' days from 'start' (0 = Sunday)?
function dayAfter(int $start, int $later): int {
    return ($start + $later) % 7;           // laps vanish, remainder stays
}

// A mod that stays in 0..m-1 even for negative numbers.
function mod(int $a, int $m): int {
    return (($a % $m) + $m) % $m;
}

echo "17 days after Sunday: " . $DAYS[dayAfter(0, 17)] . "
";
echo "100 days after Sunday: " . $DAYS[dayAfter(0, 100)] . "
";
echo "2 days before Monday (PHP %): " . (-1 % 7) . "
";      // -1, surprising!
echo "2 days before Sunday: " . $DAYS[mod(0 - 2, 7)] . "
";  // Fri

// Reducing early gives the same answer as reducing at the end.
$a = 123456; $b = 654321; $m = 1000;
echo (($a * $b) % $m) . " == " . ((($a % $m) * ($b % $m)) % $m) . "
";

JavaScript

const DAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

// Which weekday is it, 'later' days from 'start' (0 = Sunday)?
function dayAfter(start, later) {
  return (start + later) % 7;               // laps vanish, remainder stays
}

// A mod that stays in 0..m-1 even for negative numbers.
function mod(a, m) {
  return ((a % m) + m) % m;
}

console.log("17 days after Sunday: " + DAYS[dayAfter(0, 17)]);
console.log("100 days after Sunday: " + DAYS[dayAfter(0, 100)]);
console.log("-1 % 7 in JS: " + (-1 % 7));                      // -1, surprising!
console.log("2 days before Sunday: " + DAYS[mod(0 - 2, 7)]);   // Fri

// Reducing early gives the same answer as reducing at the end.
const a = 123456, b = 654321, m = 1000;
console.log(((a * b) % m) + " == " + (((a % m) * (b % m)) % m));

Java

public class Main {
    static final String[] DAYS = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

    // Which weekday is it, 'later' days from 'start' (0 = Sunday)?
    static int dayAfter(int start, int later) {
        return (start + later) % 7;               // laps vanish, remainder stays
    }

    // A mod that stays in 0..m-1 even for negative numbers.
    static long mod(long a, long m) {
        return ((a % m) + m) % m;
    }

    public static void main(String[] args) {
        System.out.println("17 days after Sunday: " + DAYS[dayAfter(0, 17)]);
        System.out.println("100 days after Sunday: " + DAYS[dayAfter(0, 100)]);
        System.out.println("-1 % 7 in Java: " + (-1 % 7));                          // -1, surprising!
        System.out.println("2 days before Sunday: " + DAYS[(int) mod(0 - 2, 7)]);   // Fri

        // Reducing early gives the same answer as reducing at the end.
        long a = 123456, b = 654321, m = 1000;
        System.out.println(((a * b) % m) + " == " + (((a % m) * (b % m)) % m));
    }
}

Go

package main

import "fmt"

var days = []string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}

// dayAfter: which weekday is it, 'later' days from 'start' (0 = Sunday)?
func dayAfter(start, later int) int {
	return (start + later) % 7 // laps vanish, remainder stays
}

// mod stays in 0..m-1 even for negative numbers.
func mod(a, m int) int {
	return ((a % m) + m) % m
}

func main() {
	minusOne := -1
	fmt.Println("17 days after Sunday:", days[dayAfter(0, 17)])
	fmt.Println("100 days after Sunday:", days[dayAfter(0, 100)])
	fmt.Println("-1 % 7 in Go:", minusOne%7)                // -1, surprising!
	fmt.Println("2 days before Sunday:", days[mod(0-2, 7)]) // Fri

	// Reducing early gives the same answer as reducing at the end.
	a, b, m := 123456, 654321, 1000
	fmt.Printf("%d == %d\n", (a*b)%m, ((a%m)*(b%m))%m)
}

Time: O(1) per operation · Extra space: O(1). One remainder is a single step, no matter how large the number.

Watch out for

  • Assuming % never gives a negative result. In PHP and JavaScript, -1 % 7 is -1.
  • Dividing instead of taking a remainder, or mixing up quotient (laps) and remainder (leftover).
  • Forgetting that modular division is tricky: you cannot just divide remainders.

Quick check

  1. What is 17 mod 5?
    • 3
    • 2
    • 12
  2. Today is Sunday. Which day is it 14 days later?
    • Sunday
    • Monday
    • Saturday
  3. What range of values can x % 7 produce (for non-negative x)?
    • 1 to 7
    • 0 to 7
    • 0 to 6