Why multiply by a prime before xoring in many GetHashCode Implementations?

前端 未结 4 2121
既然无缘
既然无缘 2021-01-06 10:33

I understand that multiplication by a large number before xoring should help with badly distributed operands but why should the multiplier be a prime?

4条回答
  •  执笔经年
    2021-01-06 11:02

    There's a good article on the Computing Life blog that discusses this topic in detail. It was originally posted as a response to the Java hashCode() question I linked to in the question. According to the article:

    Primes are unique numbers. They are unique in that, the product of a prime with any other number has the best chance of being unique (not as unique as the prime itself of-course) due to the fact that a prime is used to compose it. This property is used in hashing functions.

    Given a string “Samuel”, you can generate a unique hash by multiply each of the constituent digits or letters with a prime number and adding them up. This is why primes are used.

    However using primes is an old technique. The key here to understand that as long as you can generate a sufficiently unique key you can move to other hashing techniques too. Go here for more on this topic about hashes without primes.

提交回复
热议问题