Integer Overflow, Precision, and Safe Arithmetic

Sanjeev SharmaSanjeev Sharma
3 min read

Advertisement

Integer Overflow Prevention

Common Overflow Scenarios

  1. a * b where both are int (~10^9): product overflows int (max ~2*10^9)
  2. n * (n-1) for n = 10^5: up to 10^10, needs long long
  3. Distance formulas: dx^2 + dy^2 can overflow
  4. Factorial: 20! > 2^63

C++ Safe Practices

#include <bits/stdc++.h>
using namespace std;

// Always use long long for large computations
long long safe_mul(long long a, long long b) {
    return a * b;  // both are ll, no overflow up to ~9*10^18
}

// Check before multiplying
bool will_overflow(long long a, long long b) {
    if (a == 0 || b == 0) return false;
    return a > LLONG_MAX / b;
}

// __int128 for very large intermediates
__int128 big_computation(long long a, long long b, long long c) {
    return (__int128)a * b * c;
}

// Binary search on answer (integer)
int binarySearchAnswer(int lo, int hi, auto valid) {
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;  // NOT (lo+hi)/2 to avoid overflow!
        if (valid(mid)) hi = mid;
        else lo = mid + 1;
    }
    return lo;
}

// Modular multiplication (when MOD^2 > LLONG_MAX)
long long mulmod(long long a, long long b, long long mod) {
    return (__int128)a * b % mod;
}

Python (No Overflow Concern)

# Python integers are arbitrary precision
# But float precision matters!

# Float comparison: never use ==
def approx_equal(a, b, eps=1e-9):
    return abs(a - b) < eps

# Avoid float: use fractions for exact rational arithmetic
from fractions import Fraction
a = Fraction(1, 3)
b = Fraction(2, 3)
print(a + b)  # Fraction(1, 1) = 1 exactly

# Integer square root (exact)
import math
def isqrt(n): return math.isqrt(n)  # Python 3.8+

# Check if n is perfect square
def is_perfect_square(n):
    r = math.isqrt(n)
    return r * r == n

Java Implementation

public class SafeArith {
    // Use Math.multiplyExact to detect overflow
    public static long safeMul(long a, long b) {
        return Math.multiplyExact(a, b); // throws ArithmeticException on overflow
    }

    // Or use BigInteger
    import java.math.BigInteger;

    public static BigInteger bigMul(long a, long b) {
        return BigInteger.valueOf(a).multiply(BigInteger.valueOf(b));
    }

    // Integer sqrt
    public static long isqrt(long n) {
        long r = (long) Math.sqrt(n);
        while (r * r > n) r--;
        while ((r+1) * (r+1) <= n) r++;
        return r;
    }
}

Binary Search on Answer Template

def min_feasible(lo, hi, feasible):
    while lo < hi:
        mid = (lo + hi) // 2
        if feasible(mid):
            hi = mid
        else:
            lo = mid + 1
    return lo

# Example: minimum largest sum when splitting array into k parts
def splitArray(nums, k):
    def feasible(cap):
        parts, cur = 1, 0
        for n in nums:
            if n > cap: return False
            if cur + n > cap:
                parts += 1
                cur = 0
            cur += n
        return parts <= k

    return min_feasible(max(nums), sum(nums), feasible)

LeetCode Problems

  • 69. Sqrt(x) — binary search on answer
  • 1201. Ugly Number III — LCM + inclusion-exclusion
  • 29. Divide Two Integers — no multiplication overflow tricks

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro