I have to turn this formula into java code:
It would be much easier if I could use libraries such as Math.BigInteger but unfortunately I should do this without it. Some similar question on stackoverflow suggested to write an own bignum library but I want to do it without it.
Right now, my progress is at this step:
int h(String s) {
long value = 1;
int mod = ht.length;
for (int i=0; i < s.length()-1; i++) {
h += s.charAt(i) * Math.pow(256,i);
}
return (int) h % mod;
}
I know that the values of the power gets pretty quick out of the integer range so I thought about writing an own method which calculates the power and modulo of the value. My mathematical knowledge just isn't good enough to know when to use the modulo and how to easy things up.
Thanks in advance!
If you go from the back, you don't have to take any powers at all. Simply multiplying by 256 at each step will have the same effect (values from the back "accumulate" more multiplications, raising them to the required powers). Eg (not tested)
Also note that
ht.length
should not be a power of two (so you can't skip the modulo reduction in the loop, which you could ifht.length
was a power of two), because if it's a power of two then the hash depends on (at most) the first 4 characters, which is obviously bad.