Why use a prime number as the hash table size
1 min readAug 20, 2020
A quick answer
Use a prime number as the hash table size will on average give you the best distribution of hash values to hash buckets [1].
An example
For the hash table, usually, we have more keys than the hash table size. We’d like to have a quick comparison by using this simple example
keys(even numbers) : 2, 4, 6, 8, 10, 12, 14, 16, 18, 20
hashtable size = 10 : 2, 4, 6, 8, 0, 2, 4, 6, 8, 0
hashtable size = 11 : 2, 4, 6, 8, 10, 1, 3, 5, 7, 9
Detail explanations
See[1] and [2]
Reference
[1]https://www.quora.com/Why-should-the-size-of-a-hash-table-be-a-prime-number
[2]https://stackoverflow.com/questions/3980117/hash-table-why-size-should-be-prime