Skip to lesson

Modular arithmetic

Combinatorial and dynamic programming answers often grow far past 64-bit long limits (for example, 100! has 158 digits). To test your algorithm rather than BigInteger memory speed, online judges ask for the answer modulo M = 1 000 000 007.

Why 1_000_000_007 and Modular Add, Subtract, Multiply

Modular arithmetic keeps only the remainder after dividing by a number m, such as 1_000_000_007, so large results fit in a long without overflow.

The constant MOD = 1_000_000_007 (10⁹ + 7) is chosen for three practical reasons, explained after the code.

Example 1 · Modular Addition, Multiplication, and Factorial Modulo 1e9+7

ModularArithmeticBasicsDemo.javaJava
public class ModularArithmeticBasicsDemo {    public static final int MOD = 1_000_000_007;
    public static int modAdd(int a, int b) {        return (a + b) % MOD;    }
    public static int modMul(int a, int b) {        return (int) (((long) a * b) % MOD);    }
    public static int factorialMod(int n) {        int result = 1;        for (int i = 2; i <= n; i++) {            result = modMul(result, i);        }        return result;    }
    public static void main(String[] args) {        int x = 800_000_000;        int y = 500_000_000;        System.out.println("modAdd(8e8, 5e8) = " + modAdd(x, y));        System.out.println("modMul(8e8, 5e8) = " + modMul(x, y));        System.out.println("20! mod 1e9+7    = " + factorialMod(20));        System.out.println("100! mod 1e9+7   = " + factorialMod(100));    }}
Output
modAdd(8e8, 5e8) = 299999993
modMul(8e8, 5e8) = 200000021
20! mod 1e9+7    = 146326063
100! mod 1e9+7   = 437918130

What this code does

  • Without (long) a * b, 800_000_000 * 500_000_000 overflows 32-bit int before % MOD is applied.
  • Reducing at every step lets factorialMod(100) compute the exact remainder of a 158-digit number using a single int variable.

First, it is just below 2³⁰, so any reduced remainder 0 ≤ a, b < M fits in a 32-bit int, and even their sum a + b < 2 × 10⁹ + 14 fits in a signed 32-bit int without overflowing. Second, the product of two reduced values satisfies a × b < 10¹⁸ + 1.4 × 10¹⁰, which fits safely inside a 64-bit signed long (Long.MAX_VALUE ≈ 9.22 × 10¹⁸). Third, 10⁹ + 7 is a prime number, which guarantees that every non-zero remainder has a multiplicative inverse.

Addition, subtraction, and multiplication preserve remainders when you reduce at every intermediate step rather than only at the end:

  • Modular addition: (a + b) mod M = ((a mod M) + (b mod M)) mod M.
  • Modular multiplication: (a × b) mod M = ((a mod M) × (b mod M)) mod M — always cast to long before multiplying two int values!
  • Modular subtraction: (a - b) mod M = ((a mod M) - (b mod M) + M) mod M.
  • Warning: division does not distribute over %. Never write (a / b) % M; modular division requires multiplying by the modular inverse of b.

Negative Results of % in Java

In mathematics, x mod M always lies in 0 … M - 1. In Java, however, the % operator computes the truncated remainder whose sign matches the left operand (the dividend): -3 % 5 evaluates to -3, not 2!

Example 2 · Fixing Negative Remainders in Java

NegativeRemainderFixDemo.javaJava
public class NegativeRemainderFixDemo {    public static final int MOD = 1_000_000_007;
    public static int safeMod(long x, int mod) {        return (int) (((x % mod) + mod) % mod);    }
    public static int modSub(int a, int b) {        return (a - b + MOD) % MOD;    }
    public static void main(String[] args) {        System.out.println("Raw -17 % 5          = " + (-17 % 5));        System.out.println("safeMod(-17, 5)      = " + safeMod(-17, 5));        System.out.println("Math.floorMod(-17,5) = " + Math.floorMod(-17, 5));
        int a = 100;        int b = 500;        System.out.println("Broken (100 - 500) % MOD = " + ((a - b) % MOD));        System.out.println("modSub(100, 500)         = " + modSub(a, b));    }}
Output
Raw -17 % 5          = -2
safeMod(-17, 5)      = 3
Math.floorMod(-17,5) = 3
Broken (100 - 500) % MOD = -400
modSub(100, 500)         = 999999607

What this code does

  • In prefix-sum or rolling-hash algorithms where you subtract an earlier prefix from a later prefix modulo MOD, the difference curr - prev is often negative even though the true un-modded difference was positive.
  • Adding MOD before taking % MOD restores the true positive remainder 999_999_607.
  • When 0 ≤ a, b < M are already reduced: (a - b + M) % M is always in [0, M - 1].
  • When x can be any signed int or long: ((x % M) + M) % M or Math.floorMod(x, M).
  • Why two % M operations in ((x % M) + M) % M? The inner x % M brings x into (-M, M); adding M shifts negatives into (0, M) and positives into [M, 2M); the outer % M wraps [M, 2M) back to [0, M).

This catches programmers off guard during modular subtraction: if a = 20 and b = 50 (both already reduced modulo 100), then (a - b) % 100 evaluates -30 % 100 = -30. To force any integer x (positive or negative) into the canonical range [0, M - 1], use ((x % M) + M) % M or Java's built-in Math.floorMod(x, M).

Find the bug

Find the modular bug

Each snippet has one wrong line. Click it.

The result should always be between 0 and 99.

Round 1 of 3

Fast Modular Power (Binary Exponentiation)

Computing a^b mod M by multiplying a by itself b times takes O(b) time, which times out when b = 10⁹ or 10¹⁸.

  1. Hand trace of modPow(3, 13, 100) (3¹³ mod 100, where 13 = 1101₂): initialize res = 1, base = 3, exp = 13.
  2. Round 1 (exp = 13, bit 0 is 1): res = (1 * 3) % 100 = 3; square base = (3 * 3) % 100 = 9; shift exp = 6.
  3. Round 2 (exp = 6, bit 0 is 0): res stays 3; square base = (9 * 9) % 100 = 81; shift exp = 3.
  4. Round 3 (exp = 3, bit 0 is 1): res = (3 * 81) % 100 = 43; square base = (81 * 81) % 100 = 61; shift exp = 1.
  5. Round 4 (exp = 1, bit 0 is 1): res = (43 * 61) % 100 = 23; square base = (61 * 61) % 100 = 21; shift exp = 0. Return 23.

Example 3 · Brute force: multiply b times (O(b) time, O(1) space)

ModPowRepeatedMultiply.javaJava
public class ModPowRepeatedMultiply {    public static long modPow(long base, long exp, long mod) {        long result = 1 % mod;        for (long i = 0; i < exp; i++) {            result = (result * base) % mod;        }        return result;    }
    public static void main(String[] args) {        System.out.println("3^13 mod 100 = " + modPow(3, 13, 100));        System.out.println("2^1000000 mod 1e9+7 = " + modPow(2, 1_000_000, 1_000_000_007L));    }}
Output
3^13 mod 100 = 23
2^1000000 mod 1e9+7 = 235042059

What this code does

  • The loop multiplies by the base once per unit of the exponent, reducing modulo mod each time to avoid overflow.
  • It is fine for an exponent of a million but would need a billion steps for 2^1 000 000 000.

Example 4 · Better: recursive squaring (O(log b) time, O(log b) stack space)

ModPowRecursive.javaJava
public class ModPowRecursive {    public static long modPow(long base, long exp, long mod) {        if (exp == 0) {            return 1 % mod;        }        long half = modPow(base, exp / 2, mod);        long result = (half * half) % mod;        if (exp % 2 == 1) {            result = (result * (base % mod)) % mod;        }        return result;    }
    public static void main(String[] args) {        System.out.println("3^13 mod 100 = " + modPow(3, 13, 100));        System.out.println("2^1000000000 mod 1e9+7 = " + modPow(2, 1_000_000_000L, 1_000_000_007L));    }}
Output
3^13 mod 100 = 23
2^1000000000 mod 1e9+7 = 140625001

What this code does

  • The exponent is halved at every call: a^b is the square of a^(b/2), times one extra a when b is odd.
  • It is faster because only about 30 calls are needed for b = 10⁹. The price is a call stack of that depth.

Example 5 · Optimal: iterative binary exponentiation (O(log b) time, O(1) space)

FastModularPowerDemo.javaJava
public class FastModularPowerDemo {    public static final long MOD = 1_000_000_007L;
    public static long modPow(long base, long exp, long mod) {        long result = 1 % mod;        base = ((base % mod) + mod) % mod;        while (exp > 0) {            if ((exp & 1L) == 1L) {                result = (result * base) % mod;            }            base = (base * base) % mod;            exp >>= 1;        }        return result;    }
    public static void main(String[] args) {        System.out.println("3^13 mod 100         = " + modPow(3, 13, 100));        System.out.println("2^10 mod 1000        = " + modPow(2, 10, 1000));        System.out.println("2^1000000000 mod 1e9+7 = " + modPow(2, 1_000_000_000L, MOD));        System.out.println("5^0 mod 1            = " + modPow(5, 0, 1));    }}
Output
3^13 mod 100         = 23
2^10 mod 1000        = 24
2^1000000000 mod 1e9+7 = 140625001
5^0 mod 1            = 0

What this code does

  • 2^1_000_000_000 has over 300 million digits, yet modPow finishes in just 30 loop iterations because ⌊ log₂(10⁹)⌋ + 1 = 30.
  • Initializing result = 1 % mod correctly handles the edge case mod == 1 (where every remainder modulo 1 is 0).
  • It does the same halving as the recursive version, but in a loop, so no call stack is needed.

Binary exponentiation (exponentiation by squaring) decomposes the exponent b into its binary bits: for example, a¹³ = a^(1101₂) = a⁸ · a⁴ · a¹. By repeatedly squaring the base (a¹, a², a⁴, a⁸, …) and multiplying into the result whenever the current lowest bit of b is 1, we compute a^b mod M in O(log b) multiplications and O(1) space.

Always reduce base %= mod before entering the loop in case the initial base is ≥ 10⁹ + 7, so the very first base * base cannot overflow long.

Next step

Check your understanding

10 quick questions