Sobes.tech
Junior — Middle

Can you give an example of a hash function for an integer?

sobes.tech AI

Answer from AI

A simple hash function for an integer can be as straightforward as taking the remainder when dividing by the size of the hash table. For example:

unsigned int hash(int key, unsigned int table_size) {
    return (unsigned int)key % table_size;
}

This approach is often used to distribute keys across a fixed number of buckets in a hash table. To improve the quality of hashing, more complex functions can be used, such as multiplication by a constant and taking the fractional part, but for basic understanding, this is sufficient.