To generate a hash function, Map a key k into one of m slots by taking the remainder of k divided by m. That is, the hash function is
h(k) = k mod m.
I have read at several places that a good choice of m will be
Edit: As a summary, primes are used because you have the best chance of obtaining a unique value when multiplying values by the prime number chosen and adding them all up. For example given a string, multiplying each letter value with the prime number and then adding those all up will give you its hash value.
For hashing, prime numbers are used since they provide a better chance of creating unique values for a hash function.
From Introduction to algorithms :
When using the division method we avoid certain values of m. For example m should not be power of 2. Since if m=2^p then h(k) is p lowest-order bits of k. Unless it is known that all low-order p-bit patterns are equally likely,
it is better to make a hash function depend on all bits of the key.
As you se from the below image if i chose 2^3 which mean p=3 and m=8. The hashed keys are only dependent to lowest 3(p) bits which is bad because when you hash you want to include as much data as possible for a good distribution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With