Skip to contentKEEP THE CRAFTTHE SANCTUARY

Modular Arithmetic

Preserve a remainder class while adding, multiplying or exponentiating integers. Separate modular equivalence from ordering and division, and trace how exponent bits control repeated squaring.

1 practice exercise3 interview problems

Recognize it when A counting task asks for its answer modulo a fixed positive integer.

Checking your account…

Modular Arithmetic Code Labs

Work with Equivalence Classes

Two integers are congruent modulo m when their difference is divisible by m. Addition and multiplication may reduce operands or results without changing the equivalence class.

Normalize After Every Operation

In Python, x modulo positive m already lies from zero through m minus one. Normalize intermediate additions and products to keep representatives bounded. Congruence does not preserve ordinary order comparisons.

Trace Modular Accumulation

Reference
def modular_sum_trace(values,modulus):
    remainder=0;trace=[]
    for value in values:remainder=(remainder+value)%modulus;trace.append(remainder)
    return trace
Practice

Implement modular_sum_trace(values,modulus). Return the normalized running remainder after each value. modulus must be a positive integer.

Public tests

  • Normalize negative and positive additions

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Modular Accumulation

def modular_sum_trace(values,modulus):
    remainder=0;trace=[]
    for value in values:remainder=(remainder+value)%modulus;trace.append(remainder)
    return trace

Multiply and Exponentiate Safely

Repeated squaring computes an exponent in O(log exponent): multiply the result for set exponent bits, square the base each step, and reduce both products modulo m.

Compute Fast Modular Power

Reference
def modular_power(base,exponent,modulus):
    result=1%modulus;base%=modulus
    while exponent:
        if exponent&1:result=result*base%modulus
        base=base*base%modulus;exponent//=2
    return result
Practice

Implement modular_power(base,exponent,modulus) for a nonnegative integer exponent using repeated squaring. modulus must be a positive integer.

Public tests

  • Square and multiply under the modulus

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Compute Fast Modular Power

def modular_power(base,exponent,modulus):
    result=1%modulus;base%=modulus
    while exponent:
        if exponent&1:result=result*base%modulus
        base=base*base%modulus;exponent//=2
    return result

Consume the Bits of Exponent Five

Run the existing modular-power Lab with base 3, exponent 5 and modulus 7. Binary 5 is 101, so only the first and last iterations multiply the result. We never construct the full integer power.

Step Executed statement State Why
Initialize result=1%modulus;base%=modulus result=1, base=3, exponent=5 The result represents the empty product; base is normalized.
Odd bit if exponent&1:result=result*base%modulus result=3 The lowest bit contributes one factor 3.
Square and halve base=base*base%modulus;exponent//=2 base=2, exponent=2 The unconsumed power becomes 2 squared modulo 7.
Zero bit base=base*base%modulus;exponent//=2 result=3, base=4, exponent=1 The even exponent contributes no extra factor before squaring.
Last bit if exponent&1:result=result*base%modulus result=5, base=4, exponent=1 3*4 is 12, represented by 5 modulo 7; this conditional changes result only.
Finish last iteration base=base*base%modulus;exponent//=2 result=5, base=2, exponent=0 Squaring and halving are outside the odd-bit conditional and run after every bit.
Modulus-one call result=1%modulus result=0 Exponent zero returns the normalized identity, including modulus 1.
Print Output
print(modular_power(3, 5, 7)) 5
print(modular_power(4, 0, 1)) 0

The proof concerns congruence, not ordering: 9 < 12 but 9 % 5 > 12 % 5. Keep unreduced values when an ordinary comparison is part of the problem. For a direct modular power, the maintained built-in pow(base, exponent, modulus) is usually the practical choice.

Use Inverses Only When They Exist

Division modulo m means multiplying by an inverse. An inverse of a exists only when gcd(a,m) equals one; prime-modulus shortcuts require the prime and nonzero premises.

Explain It in an Interview

Say: “I preserve the same remainder class after each operation. Binary exponentiation consumes one exponent bit per step and reduces products immediately.” State modulus positivity, zero exponent, negative base normalization, and inverse existence.

Python Version Note

Python 3.11+

The code uses standard Python syntax and containers supported by the browser Judge. The Modular Arithmetic proof does not depend on a minor Python release.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Binary modular exponentiationO(1 + log(exponent + 1))O(1 + log(exponent + 1))Counts bounded modular arithmetic operations; exponent zero still initializes the result.

Space

O(1) scalar slots; integer bit storage depends on modulus and exponent.

Assumptions

  • Python multiplication and remainder are not constant time for arbitrarily large integers.
  • The accumulation trace takes O(n) arithmetic steps and stores O(n) remainders.

Invariants Worth Saying Aloud

  1. Reducing an operand changes it by a multiple of the modulus, so addition and multiplication preserve congruence.
  2. During exponentiation, result * base**exponent remains congruent to the requested original power.
  3. With positive modulus, every stored remainder is in [0, modulus).

When To Use Or Avoid Modular Arithmetic

Use It When

  • Reduce sums and products when only a remainder class is required.
  • Use binary exponentiation for a nonnegative exponent; require a coprime divisor before modular inversion.

Choose Another Tool When

  • Do not reduce costs or values before ordinary minimum, maximum or order comparisons: modulo does not preserve order.
  • Do not replace modular division with integer //; an inverse may not exist.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Returning 1 without reducing the zero-exponent identity

For modulus 1, even the multiplicative identity is represented by 0. Returning literal 1 is outside the remainder range.

Prevent it: Initialize result to 1 % modulus before inspecting exponent bits.

Avoid

result = 1

Use instead

result = 1 % modulus

Using a signed remainder convention for a positive modulus

Negating abs(value) % modulus gives -3 for value -3 and modulus 5; the Python normalized representative is 2.

Prevent it: Use value % modulus directly when modulus is positive.

Avoid

remainder = -(abs(value) % modulus)

Use instead

remainder = value % modulus

Treating floor division as modular division

3 // 2 gives 1, but division by 2 modulo 5 means multiplying by its inverse 3, giving 4.

Prevent it: Check coprimality and use an inverse. Python pow(divisor, -1, modulus) rejects a noninvertible divisor.

Avoid

result = (a // b) % modulus

Use instead

result = (a * pow(b, -1, modulus)) % modulus

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.