Numbers and bits · 4 / 15 Theory

Modular arithmetic

Modular arithmetic works with remainders: “what time will it be in 100 hours” is (hour + 100) % 24. It is the basis of check codes, pseudo-random number generators and cryptography.

print(7 % 3, -7 % 3, 7 % -3)         # 1 2 -2   in Python the remainder follows the divisor
print((10**18 + 7) % 13)             # 8
print(pow(2, 10, 1000))              # 24       2**10 % 1000 without giant numbers

def power_mod(base, exp, mod):
    result = 1
    base %= mod
    while exp:
        if exp & 1:                  # current bit of the exponent is 1
            result = result * base % mod
        base = base * base % mod     # base, base², base⁴, base⁸…
        exp >>= 1
    return result

print(power_mod(3, 200, 13), pow(3, 200, 13))   # 9 9
print(pow(3, -1, 7))                 # 5        modular inverse (Python 3.8+): 3*5 % 7 == 1

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a
print(gcd(48, 18))              # 6
  • In Python % returns a result with the sign of the divisor, so -7 % 3 is 2 and you never need to “fix” negatives.
  • You can reduce modulo m at any step: (a * b) % m == ((a % m) * (b % m)) % m. That way numbers never become huge.
  • Fast exponentiation needs about log2(exp) multiplications instead of exp. Python already includes it as pow(base, exp, mod).
  • The modular inverse of a exists only if a and m are coprime; it is computed with extended Euclid or with pow(a, -1, m).

You practice it in Modular exponentiation and Modular inverse.