TExcelTAD
Home › Data Structures: Hashing, Search Trees, B-Trees & Union-Find › Hash Functions: Division and Multiplication

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 c0c1…cℓ−1c_0 c_1 \ldots c_{\ell-1} can be read as a number in radix RR (for example R=256R = 256 for bytes),

k=c0Rℓ−1+c1Rℓ−2+⋯+cℓ−1k = c_0 R^{\ell-1} + c_1 R^{\ell-2} + \cdots + c_{\ell-1}

computed by Horner's rule, k=(⋯((c0)R+c1)R+⋯ )R+cℓ−1k = (\cdots((c_0) R + c_1) R + \cdots) R + c_{\ell-1}. 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

h(k)=k mod mh(k) = k \bmod m

One division, very fast. Its quality depends entirely on mm.

  • Avoid m=2pm = 2^p. Then k mod 2pk \bmod 2^p is just the lowest pp bits of kk, 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 mm with small factors for the same reason: keys that share a factor with mm 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 282^8 and m=28−1=255m = 2^8 - 1 = 255, then 256≡1(mod255)256 \equiv 1 \pmod{255}, so hh 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.

python · try it yourself
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 m=1024m = 1024 only the slots that are multiples of 8 are reachable; with m=1000m = 1000 (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

h(k)=⌊m(kA mod 1)⌋for a constant 0<A<1h(k) = \left\lfloor m \left( kA \bmod 1 \right) \right\rfloor \qquad \text{for a constant } 0 < A < 1

Here kA mod 1kA \bmod 1 is the fractional part of kAkA, a number in [0,1)[0, 1), scaled to a slot. Now the choice of mm is not critical, and m=2pm = 2^p is convenient. With ww-bit machine words the method needs no floating point at all: let s=⌊A⋅2w⌋s = \lfloor A \cdot 2^w \rfloor; then k⋅sk \cdot s is a 2w2w-bit product, its low ww bits hold the fraction, and the slot is the top pp bits of that low word:

h(k)=((k⋅s) mod 2w)≫(w−p)h(k) = \left( (k \cdot s) \bmod 2^w \right) \gg (w - p)

Donald Knuth suggests A≈(5−1)/2≈0.618A \approx (\sqrt{5} - 1)/2 \approx 0.618; with w=32w = 32 that gives s=2654435769s = 2654435769. 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.

python · try it yourself
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 m=1024m = 1024, but fewer than the roughly 640 a random function would hit with 1000 keys in 1024 slots. The reason is instructive: for keys 8i8i, the fractional part of 8iA8iA is that of i⋅(8A mod 1)i \cdot (8A \bmod 1), and 8A mod 1≈0.9448A \bmod 1 \approx 0.944 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 2w2^w" 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.

cpp · try it yourself
#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.

python · try it yourself
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 m=2pm = 2^p a poor choice for the division method?

  1. Division by a power of 2 is slow
  2. k mod 2pk \bmod 2^p keeps only the lowest pp bits of kk, so keys that agree in those bits always collide
  3. Powers of 2 are not prime, so the table cannot be full
  4. It is fine; any mm works equally well

In the multiplication method with w=32w = 32 and m=2pm = 2^p, which bits of the product k⋅sk \cdot s form the slot?

  1. the lowest pp bits
  2. the highest pp bits of the low 32-bit word
  3. the highest pp bits of the full 64-bit product
  4. all 64 bits, reduced mod mm

With the division method on strings read in radix 256, why is m=255m = 255 a bad choice?

  1. 255 is too small
  2. 256≡1(mod255)256 \equiv 1 \pmod{255}, so the hash reduces to the character sum and every permutation collides
  3. 255 is prime
  4. Strings cannot be read as numbers