My hashcode function for string is as follows
hashVal=(127*hashVal+key.charAt(i))%1690879开发者_运维百科9
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 ?
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
精彩评论