algorithm - 通过折叠然后除以素数来散列 key ?

标签 algorithm hash hashcode hash-function

我想使用一个使用 3 个步骤的简单散列函数对以下键“LOWELL”进行散列:

第 1 步:将 key 转换为数字。

LOWELL = | L | O | W | E | L | L | | | | | | |
ASCII code: 76 79 87 69 76 76 32 32 32 32 32 32

my question here why it added more 6 empty positions with fixed ASCII code 32

第 2 步:折叠并相加(切下数字并相加 他们在一起)

7679|8769|7676|3232|3232|3232|
7679+8769+7676+3232+3232+3232 = 33,820

第三步:用质数取模

33,820 模 19937 = 13,883

Another question here for why dividing by prime numbers i found this answer : Dividing by a number is good when there are sequences of consecutive numbers. If there are many dierent sequences of consecutive numbers, dividing by a number that has many small factors may result in lots of collisions. A prime number is a better choice. but i didn't get it

第四步:除以地址空间的大小(最好是素数)。 13,883 模 101 = 46

finally why it divided the address space ?!

您可以找到详细步骤here (幻灯片 350) 非常感谢您的帮助

最佳答案

由于您的地址空间仅包含 101 个槽,因此您不能将记录放在地址超过此限制的位置。

因此,您需要注意将哈希函数(在您的情况下为 13,883)的输出除以地址空间,以确保记录的位置落在允许的地址空间内.

因此 h(s) % address_space 将始终在您的地址空间内提供允许的位置。

关于您的第一个问题,为什么我们在散列中使用质数,这个线程将帮助您: Why use a prime number in hashCode?

关于algorithm - 通过折叠然后除以素数来散列 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37212536/

相关文章:

c++ - 散列范围为 10 亿的 100 个不同的值

java - 为什么我们需要检查两次哈希码?

java - kotlin 结构相等性检查父类(super class)型吗?

c++ - 如何计算指针的哈希值?

python-3.x - 生成缩短网址的代码/算法是什么?

c# - 在 C# 中使用 SHA1 算法进行散列

algorithm - 棘手的谷歌面试问题

python - “help” 通过将 2 个特征绑定(bind)在一起的决策树

python - 对 python 列表的子集进行排序,使其具有与其他列表中相同的相对顺序

algorithm - 不规则多边形的高效打包算法