IMPORTANT NOTICE:
This is not a discussion thread for people to give me their opinion about hashing. I just need to know how to make the given function work in java — an example would be best.
PROBLEM:
Trying to hone my understanding of hash functions for a pending interview, I watch two free lectures by MIT computer science professors (http://videolectures.net/mit6046jf05_leiserson_lec08/). So after the lecture, I am trying to implement the following hash function in java.
h(k) = (A·k mod 2^w) >> (w – r)
WHERE
r: m, the size of the array, is a power of 2 such that m=2^r
w: the computer has w-bit words, such as 32-bit or 64-bit computer
k: the value I am to find a key for
A: a random odd number (prime would be great) between 2^(w-1) and 2^w
I thought this would be easy to implement in java. But when I do 2^w where w=32, I get inaccurate results in Java. In real life 2^32 = 4294967296 but not in java, which truncates the result to 2^31 - 1 or 2147483647.
Does anyone know how to fix this problem so to implement the function in Java?
EDIT:
I see a lot of the replies focus on 32. What if my computer is 64 bit? I am stuck with setting w = 32 because I am using Java?
Some of the terms are redundant because Java assumes this behaviour anyway.
In Java, integer multiplication overflows and thus does a mod
2^w(with a sign). The fact that it has a sign doesn’t matter if you are then shifting by at least one bit.Shift of
(w - r)is the same as a shift of-rin Java (the w is implied by the type)for 64-bit
I have written this example to show you can do the same thing in BigInteger and why you wouldn’t. 😉
prints