Sub topic 8
Choosing the Base and Modulus
This chapter assumes you already know the polynomial hash, the rolling update, and the Rabin-Karp loop with verification from earlier chapters. Here the question is which numbers to plug in for base and mod. Your choice decides how often false hash matches happen. Each false match costs you a wasted string comparison.
What the base must do
The base sets how much weight each character position gets. Two rules matter.
- Make the base larger than the alphabet. With
base=256and byte-sized characters, every short string maps to a distinct integer before the modulus is applied. If the base is smaller than the largest character code, different strings can collide even with no modulus at all. Python'sordreturns Unicode code points, which can be larger than 255, so 256 is not always safe there. - Pick the base at random when inputs may be hostile. A fixed, published base lets anyone compute colliding strings ahead of time. If you pick the base uniformly from a large range when the program starts, nobody can prepare such strings in advance.
What the modulus must do
The modulus is the range the hash values fall into, so it caps how many distinct hash values exist. Use a large prime.
A prime modulus gives a clean guarantee. Take two different strings of length m, hashed with a base chosen at random from 0 to p − 1. They collide only when the base is a root of their difference polynomial. That polynomial has degree at most m − 1, so it has at most m − 1 roots modulo p. The collision probability is therefore at most (m − 1)/p.
Over n windows, the expected number of false matches is about n(m − 1)/p. With p ≈ 10⁹, n = 10⁶ and m = 100, that comes to about 0.1 false matches per search.
A small modulus breaks this. A modulus of 2⁶⁴ (letting machine integers overflow) is not prime, and a later chapter shows inputs that defeat it for every base.
| Modulus | Why people use it | Caveat |
|---|---|---|
| 1_000_000_007 | Prime, and products of two values fit in 64 bits | About 1 in 10⁹ collision chance per window |
| 998_244_353 | Prime, same size class | Same as above |
| 2⁶¹ − 1 | Mersenne prime with fast reduction and much lower collision odds | Products need 128-bit arithmetic |
| 2⁶⁴ (overflow) | Free reduction | Not prime, and known strings collide for any base |
Seeing the effect of the modulus
The script below counts false matches, meaning windows whose hash equals the pattern's hash even though the text differs. It does this for three moduli on the same random text.
import random
def window_hashes(text, m, base, mod):
high = pow(base, m - 1, mod)
h = 0
for ch in text[:m]:
h = (h * base + ord(ch)) % mod
yield h
for i in range(len(text) - m):
h = ((h - ord(text[i]) * high) * base + ord(text[i + m])) % mod
yield h
def false_matches(text, pattern, base, mod):
m = len(pattern)
p = 0
for ch in pattern:
p = (p * base + ord(ch)) % mod
count = 0
for i, h in enumerate(window_hashes(text, m, base, mod)):
if h == p and text[i:i + m] != pattern:
count += 1
return count
random.seed(1)
text = "".join(random.choice("ab") for _ in range(100_000))
pattern = "abbabaabba"
for mod in (101, 10_007, 1_000_000_007):
base = random.randint(2, mod - 2)
print(mod, false_matches(text, pattern, base, mod))Expect roughly 1,000 false matches for mod 101, about 10 for 10,007, and almost always 0 for 1,000,000,007. Verification keeps the results correct in every case. A poor modulus only makes the search slower.
Common mistakes
- Using a composite modulus such as 10⁹ (not prime) or a power of two.
- Picking the base from a narrow range, such as 2 to 10, which makes collisions easier to find.
- Choosing a modulus so large that
hash * baseoverflows a fixed-width integer. The next chapter covers how to handle this.
Exercise
You search a text of 10^7 characters for a pattern of length 1,000, using a random base and the prime modulus 1,000,000,007. Roughly how many false hash matches should you expect, and does it matter?
Show answer
About n(m − 1)/p ≈ 10^7 × 999 / 10^9 ≈ 10. Correctness is not affected because each match is verified. Each false match costs one extra comparison of up to 1,000 characters, about 10^4 character comparisons in total, which is negligible.
Exercise
Why is base = 31 with mod = 2^64 a poor choice for hashing user-submitted strings, even though it is fast?
Show answer
The modulus 2^64 is not prime, so the (m − 1)/p bound does not apply, and strings are known that collide under it for every base. A fixed base also lets attackers prepare colliding inputs in advance.