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

前端 未结 4 2149
既然无缘
既然无缘 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:06

    I'm not sure exactly which algorithm you're talking about, but typically the constants in such algorithms need to be relatively prime. Otherwise, you get cycles and not all the possible values show up in the result.

    The number probably doesn't need to be prime in your case, only relatively prime to some other numbers, but making it prime guarantees that. It also covers the cases where the other magic numbers change.

    For example, if you are talking about taking the last bits of some number, then the multiplier needs to not be a multiple of 2. So, 9 would work even though it's not prime.

提交回复
热议问题