Sub topic 9
Avoiding Overflow and Negative Remainders in Java and C++
This chapter assumes you already know the rolling update from the earlier chapters: subtract the outgoing character times high, multiply by the base, then add the incoming character. It also assumes you can read basic Java or C++. In Python the update works as written, because Python integers never overflow and % always returns a non-negative result. Java and C++ give you neither of those guarantees, so the same formula needs two adjustments.
Problem 1: Overflow
A Java int or C++ int holds values up to about 2.1 × 10⁹. With MOD = 1_000_000_007, a hash value can be close to 10⁹. Multiplying it by high, which is also close to 10⁹, gives about 10¹⁸. That result wraps around silently and produces a wrong hash with no error.
The fix is to store every value in a 64-bit signed integer (long in Java, long long in C++). The maximum is about 9.2 × 10¹⁸. Keep every operand below MOD before you multiply, and the product of two of them stays below 10¹⁸, which fits.
| Expression | Largest value | Fits in 64-bit signed? |
|---|---|---|
| `hash * BASE + incoming` | ≈ 2.6 × 10¹¹ | Yes |
| `outgoing * high` | ≈ 6.6 × 10¹³ (char ≤ 65535) | Yes |
| `a * b`, both `< MOD` | ≈ 10¹⁸ | Yes |
| `a * b`, unreduced | unbounded | No |
Problem 2: Negative remainders
In Java and C++, % takes the sign of the left operand, so -3 % 5 evaluates to -3, not 2. The subtraction hash - outgoing * high is often negative, and a negative hash will never equal the pattern hash, which is non-negative. The usual fix is to add MOD before the final reduction. Java also provides Math.floorMod, which always returns a non-negative result.
Java: a complete check
The program below rolls a hash across "abracadabra" and compares each rolled value with a hash computed from scratch.
public class RollDemo {
static final long MOD = 1_000_000_007L;
static final long BASE = 256L;
static long hash(String s, int from, int len) {
long h = 0;
for (int i = from; i < from + len; i++) h = (h * BASE + s.charAt(i)) % MOD;
return h;
}
static long roll(long hash, char outgoing, char incoming, long high) {
long next = (hash - (long) outgoing * high % MOD + MOD) % MOD;
return (next * BASE + incoming) % MOD;
}
public static void main(String[] args) {
String text = "abracadabra";
int m = 4;
long high = 1;
for (int i = 0; i < m - 1; i++) high = high * BASE % MOD;
long h = hash(text, 0, m);
for (int i = 0; i + m < text.length(); i++) {
h = roll(h, text.charAt(i), text.charAt(i + m), high);
System.out.println((i + 1) + " " + (h == hash(text, i + 1, m)));
}
}
}Every line prints true. If you delete + MOD, some lines print false, because those rolled hashes went negative.
C++ version
#include <cstdint>
#include <iostream>
#include <string>
const long long MOD = 1000000007LL, BASE = 256;
long long roll(long long h, unsigned char out, unsigned char in, long long high) {
long long next = (h - out * high % MOD + MOD) % MOD;
return (next * BASE + in) % MOD;
}
int main() {
std::string t = "abcd";
long long high = BASE % MOD; // BASE^(m-1) for m = 2
long long h = ('a' * BASE + 'b') % MOD;
h = roll(h, t[0], t[2], high);
std::cout << (h == ('b' * BASE + 'c') % MOD) << "\n"; // prints 1
}Exercise
In Java, hash = 5, outgoing * high % MOD = 900, and MOD = 1000000007. What does (hash - 900) % MOD return, and what does (hash - 900 + MOD) % MOD return?
Show answer
The first returns -895, because Java's % keeps the sign of the left operand. The second returns 1000000007 - 895 = 999999112, which is the correct non-negative remainder.
Exercise
Why is it safe to compute next BASE + incoming in a long without reducing next BASE first?
Show answer
After reduction, next is below about 1.0 × 10⁹. Multiplying by 256 and adding a character gives at most about 2.6 × 10¹¹, which is far below the 64-bit limit of about 9.2 × 10¹⁸.