什么整数散列函数是好的,接受一个整数哈希键?
什么整数散列函数是好的,接受一个整数哈希键?
What integer hash function are good that accepts an integer hash key?
Knuth的乘方法:
Knuth's multiplicative method:
hash(i)=i*2654435761 mod 2^32
在一般情况下,你应该选择一个乘数是(在本例 2 ^ 32
)的散列大小的顺序,也没有共同的因素吧。这样,散列函数涵盖了所有你的散列空间均匀。
In general, you should pick a multiplier that is in the order of your hash size (2^32
in the example) and has no common factors with it. This way the hash function covers all your hash space uniformly.
编辑:此散列函数的最大缺点是它preserves整除,所以如果你的整数都整除2或4(这是不常见),他们的哈希值也将如此。这是哈希表的问题 - 你可以结束了只有1/2或桶的1/4正在使用
The biggest disadvantage of this hash function is that it preserves divisibility, so if your integers are all divisible by 2 or by 4 (which is not uncommon), their hashes will be too. This is a problem in hash tables - you can end up with only 1/2 or 1/4 of the buckets being used.