哈希码函数

发布于 2024-12-06 18:23:21 字数 274 浏览 2 评论 0原文

我的字符串哈希码函数如下

hashVal=(127*hashVal+key.charAt(i))%16908799

我正在在线关注 cs61 b 讲座,当 Jonathan 教授讲述如果我们使用一个与 127 不互素的值代替 1690877 会发生什么时,我不太明白。我理解这个简单的情况他使用 127 而不是 16908799 但如果它是 127 的简单倍数呢?它如何“偏差”哈希值?偏差如何取决于公因数“x”?谁能告诉我原因吗?

My hashcode function for string is as follows

hashVal=(127*hashVal+key.charAt(i))%16908799

I am following cs61 b lectures online and I dont quite follow when Prof.Jonathan on what would happen if instead of 1690877 we would use a value that is no relatively prime with 127. I understand the simple case where he uses 127 instead of 16908799 but what if it was a simple multiple of 127 ? How would it "bias" the hashvalue ? How does the bias depend on the common factor "x" ? Can anyone suggest me the reason ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风柔一江水 2024-12-13 18:23:21

使用较小的数字并思考一下。假设您正在模数 10 的空间(而不是 16908799)中工作。您的 hashVal 只能包含数字 0-9。

例如,如果你乘以 7,你应该会看到你可以得到所有数字 0-9:

(7*0)%10 = 0
(7*1)%10 = 7
(7*2)%10 = 4
(7*3)%10 = 1
(7*4)%10 = 8
(7*5)%10 = 5
(7*6)%10 = 2
(7*7)%10 = 9
(7*8)%10 = 6
(7*9)%10 = 3

但是,如果你乘以 6(它与 10 不互质,因为它们有公因数 2),那么你不会取出所有数字 0-9,因此存在偏差:

(6*0)%10 = 0
(6*1)%10 = 6
(6*2)%10 = 2
(6*3)%10 = 8
(6*4)%10 = 4
(6*5)%10 = 0
(6*6)%10 = 6
(6*7)%10 = 2
(6*8)%10 = 8
(6*9)%10 = 4

Use smaller numbers and think it out. Say you're working in a modulus 10 space (instead of 16908799). Your hashVal can then only contain the numbers 0-9.

If you multiply by 7, for instance, you should see that you can get out all numbers 0-9:

(7*0)%10 = 0
(7*1)%10 = 7
(7*2)%10 = 4
(7*3)%10 = 1
(7*4)%10 = 8
(7*5)%10 = 5
(7*6)%10 = 2
(7*7)%10 = 9
(7*8)%10 = 6
(7*9)%10 = 3

However if you multiply by 6 (which is not relatively prime with 10 because they have the common factor 2), then you will not get all numbers 0-9 out, thus there is bias:

(6*0)%10 = 0
(6*1)%10 = 6
(6*2)%10 = 2
(6*3)%10 = 8
(6*4)%10 = 4
(6*5)%10 = 0
(6*6)%10 = 6
(6*7)%10 = 2
(6*8)%10 = 8
(6*9)%10 = 4
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文