Exercise 3: Normalizing a Negative Hash for an 8-Bucket Table — Possible Solution ==================================================================== GIVEN ------------------------------ Hash value: -41. Table size: 8 buckets. STEP 1: APPLY THE NORMALIZATION FORMULA ------------------------------ ((a % n) + n) % n, with a = -41, n = 8 Using the floored convention (this chapter's own default, matching Python and the division algorithm from Chapter 2): -41 % 8 = 7 (since -41 = 8*(-6) + 7, and 0 <= 7 < 8) Then: (7 + 8) % 8 = 15 % 8 = 7 The formula returns 7 either way here, since -41 % 8 was already non-negative under the floored convention - but applying the full formula is still correct and safe regardless of which convention produced the initial remainder. Valid bucket index: 7 STEP 2: WHAT A TRUNCATING LANGUAGE WOULD COMPUTE WITHOUT NORMALIZING ------------------------------ Per this chapter's own comparison table, a language that truncates toward zero (JavaScript, Java, or C) computes a remainder that shares the DIVIDEND's sign, not the divisor's. Since the dividend (-41) is negative, the truncating result is also negative: -41 % 8 (truncating toward zero) = -1 (since -41 / 8 truncates to -5, and -41 - (8*-5) = -41 - (-40) = -1) WHY -1 IS UNUSABLE AS AN INDEX ------------------------------ An array/bucket index of -1 is not a valid position in a table with 8 buckets (valid indices are 0 through 7). Depending on the language, this either throws an out-of-bounds error, silently wraps to the LAST bucket via language-specific negative-indexing behavior (masking the real bug rather than fixing it), or corrupts unrelated memory in a language with no bounds checking at all - none of which is the intended "the 8th bucket, safely wrapped around" behavior modular arithmetic is supposed to provide. RESULT ------------------------------ The correct, safe bucket index is 7, obtained via this chapter's own normalization formula - which returns the right answer regardless of whether the underlying language floors or truncates. WHY THIS WORKS AS AN ANSWER ------------------------------ Both the correct normalized result and the specific wrong value a truncating language would produce are computed explicitly (not just described), and the resulting problem (an invalid negative index) is explained in terms of what actually goes wrong in real code, not just labeled "incorrect."