Hash Functions: Division and Multiplication
The analysis of chaining assumed that keys land in slots as if at random. A real hash function is a fixed, fast, deterministic computation, so it cannot be random; the best it can do is to destroy the patterns that real keys have. Keys are often multiples of something, share their low bits, come in sequences, or are strings that differ in one character. A good hash function makes each of those spread over all slots.
This lesson covers the two classic designs for integer keys, the division method and the multiplication method, and how to turn strings into integers first. The next lesson, Universal Hashing, adds the randomness that the theory needs.
Keys are integers
Hash functions in this course take a non-negative integer. Anything else is first converted: a string of characters can be read as a number in radix (for example for bytes),
computed by Horner's rule, . That number is huge for a long string, so in practice every step is reduced modulo something, which is the polynomial hash used below. Unlike the character sum of Hash Tables with Chaining, it depends on the order of the characters, so anagrams no longer collide.
The division method
One division, very fast. Its quality depends entirely on .
- Avoid . Then is just the lowest bits of , and the other bits are ignored. Keys that are all multiples of 8 (aligned memory addresses, for example) use only one slot in eight.
- Avoid with small factors for the same reason: keys that share a factor with only reach the slots that are multiples of the common factor.
- A prime not too close to a power of 2 is the usual choice. If keys are strings read in radix and , then , so becomes the character sum mod 255 again and every permutation of a string collides.
The program hashes 1000 keys that are all multiples of 8 into three table sizes and counts how many slots get used.
from collections import Counter
keys = [8 * i + 4096 for i in range(1000)] # like aligned addresses
for m in [1024, 1000, 1021]:
load = Counter(k % m for k in keys)
print(f"m = {m:4}: {len(load):4} slots used, longest chain {max(load.values())}")m = 1024: 128 slots used, longest chain 8
m = 1000: 125 slots used, longest chain 8
m = 1021: 1000 slots used, longest chain 1
With only the slots that are multiples of 8 are reachable; with (which shares the factor 8 with every key) the same happens. The prime 1021 has no common factor with the keys, so consecutive multiples of 8 visit distinct slots.
The multiplication method
Here is the fractional part of , a number in , scaled to a slot. Now the choice of is not critical, and is convenient. With -bit machine words the method needs no floating point at all: let ; then is a -bit product, its low bits hold the fraction, and the slot is the top bits of that low word:
Donald Knuth suggests ; with that gives . Using this golden-ratio constant is often called Fibonacci hashing. The program implements the word version and checks it against the formula with exact fractions.
from fractions import Fraction
from collections import Counter
W, P = 32, 10 # 32-bit words, m = 2^10 = 1024 slots
S = 2654435769 # floor(0.6180339887... * 2^32)
def mult_hash(k):
return ((k * S) % 2 ** W) >> (W - P)
def mult_hash_exact(k): # floor(m * frac(k * A)) with A = S / 2^W
a = Fraction(S, 2 ** W)
frac = k * a - (k * a).numerator // (k * a).denominator
return int(2 ** P * frac)
assert all(mult_hash(k) == mult_hash_exact(k) for k in range(0, 10 ** 6, 997))
print("first keys:", [mult_hash(k) for k in range(1, 9)])
keys = [8 * i + 4096 for i in range(1000)] # the multiples of 8 from before
load = Counter(mult_hash(k) for k in keys)
print(f"multiples of 8 into m = 1024: {len(load)} slots used, longest chain {max(load.values())}")first keys: [632, 241, 874, 483, 92, 725, 334, 966]
multiples of 8 into m = 1024: 446 slots used, longest chain 4
Consecutive keys are scattered far apart. The multiples of 8 now reach 446 slots instead of the 128 the division method managed with , but fewer than the roughly 640 a random function would hit with 1000 keys in 1024 slots. The reason is instructive: for keys , the fractional part of is that of , and is close to 1, a poor multiplier. Every fixed function has key patterns it handles badly; the multiplication method only breaks the most common ones.
In C++
In C++ the reduction "mod " is free: unsigned arithmetic wraps around. The multiplication method is one multiplication and one shift, which is why it is popular in fast hash tables. The program hashes the same keys with 64-bit Fibonacci hashing, and strings with a polynomial hash.
#include <cstdint>
#include <cstdio>
#include <string>
#include <vector>
constexpr int P = 10; // m = 2^10 slots
constexpr std::uint64_t S = 11400714819323198485ull; // floor(0.618... * 2^64)
std::uint32_t fib_hash(std::uint64_t k) { return static_cast<std::uint32_t>((k * S) >> (64 - P)); }
std::uint64_t poly_hash(const std::string& s, std::uint64_t mod = 1000000007, std::uint64_t radix = 256) {
std::uint64_t h = 0;
for (unsigned char c : s) h = (h * radix + c) % mod; // Horner's rule, reduced every step
return h;
}
int main() {
std::vector<int> count(1 << P);
int used = 0, longest = 0;
for (int i = 0; i < 1000; ++i) {
int& c = count[fib_hash(8 * i + 4096)];
if (c++ == 0) ++used;
if (c > longest) longest = c;
}
std::printf("multiples of 8 into 1024 slots: %d used, longest chain %d\n", used, longest);
for (const char* w : {"cat", "act", "tac", "dog"})
std::printf("poly_hash(%s) = %llu, slot %llu of 1021\n", w,
static_cast<unsigned long long>(poly_hash(w)), static_cast<unsigned long long>(poly_hash(w) % 1021));
}multiples of 8 into 1024 slots: 446 used, longest chain 4
poly_hash(cat) = 6513012, slot 53 of 1021
poly_hash(act) = 6382452, slot 181 of 1021
poly_hash(tac) = 7627107, slot 237 of 1021
poly_hash(dog) = 6582119, slot 753 of 1021
Strings: the order of the characters must matter
Hash functions for strings run into the same patterns at a larger scale: many keys share long prefixes (user_0001, user_0002, …) or are permutations of one another. The program compares the character sum with the polynomial hash on two such key sets, counting distinct hash values in a table of 1021 slots.
from itertools import permutations
from collections import Counter
def char_sum(s, m):
return sum(map(ord, s)) % m
def poly(s, m, radix=256):
h = 0
for c in s:
h = (h * radix + ord(c)) % m
return h
anagrams = ["".join(p) for p in permutations("listen")] # 720 strings
ids = [f"user_{i:04}" for i in range(1000)]
m = 1021
for name, keys in [("anagrams of 'listen'", anagrams), ("user_0000..user_0999", ids)]:
for f in (char_sum, poly):
load = Counter(f(k, m) for k in keys)
print(f"{name:21} {f.__name__:8}: {len(keys)} keys -> {len(load):4} slots, longest chain {max(load.values())}")anagrams of 'listen' char_sum: 720 keys -> 1 slots, longest chain 720
anagrams of 'listen' poly : 720 keys -> 516 slots, longest chain 4
user_0000..user_0999 char_sum: 1000 keys -> 28 slots, longest chain 75
user_0000..user_0999 poly : 1000 keys -> 286 slots, longest chain 8
The six letters of "listen" are distinct, so its permutations are 720 distinct strings, and the character sum sends all of them to one slot. The polynomial hash spreads the anagrams well, but does poorly on the IDs: they differ only in their last four characters, each one of ten digits, and the multipliers of those positions are the powers of 256 modulo 1021, which are 1, 256, 192 and 144. The 1000 hash values therefore come from a small, structured set of sums, and crowd into 286 slots. Production hash functions (SipHash in Python and Rust, MurmurHash, xxHash) add more mixing steps, and Python additionally seeds its string hash at start-up, a practical form of the random choice studied next.
Test yourself
Why is a poor choice for the division method?
- Division by a power of 2 is slow
- keeps only the lowest bits of , so keys that agree in those bits always collide
- Powers of 2 are not prime, so the table cannot be full
- It is fine; any works equally well
In the multiplication method with and , which bits of the product form the slot?
- the lowest bits
- the highest bits of the low 32-bit word
- the highest bits of the full 64-bit product
- all 64 bits, reduced mod
With the division method on strings read in radix 256, why is a bad choice?
- 255 is too small
- , so the hash reduces to the character sum and every permutation collides
- 255 is prime
- Strings cannot be read as numbers