3

So I'm working on an assignment for my Computer Science class, and we have to basically compute strings into hash values and then modulo it by 1 million and put it into the hash table. But the value keeps overflowing and turning into negative values, anyone know how I can calculate the key?

(BTW, the hashcode is the same code that is calculated by the .hashCode function in Java)

Comments
  • 0
    Use a bigger data type, so that it doesn't overflow?
  • 0
    Take the absolute value of the hashcode I think I ran into a similar problem when doing this for algorithms
  • 0
    Use a long, or long long.
  • 0
    @Axis or mod it into a signed type. Hashes are signed to start with so the mod operation in Java must respect negatives and will produce a negative result when appropriate. So I think dumping it into a signed data type should just work.

    Although when thinking about it, if the values are overflowing something is wrong, if you mod by 1 mil, your value should always be less than 1 mil and greater than -1 mil.
  • 0
    Try doing a .hashCode of "aaaaaaaaaaa" and you'll get a negative number. You'll understand how it can overflow any variable type with the polynomial it uses.

    In the end I just used a BigInteger to store any size value. Although I also realized that it didn't have to perfectly mod as though there were no overflows, in which case I could have just modded the absolute value of the overflow value.
Add Comment