Compute the integer average of two integers a and b using only integer-type operations. The integer average is defined as the greatest integer less than or equal to the exact average (i.e., floor((a+b)/2.0)).
Assumptions and constraints:
Use only integer variables (no floating-point, no casts to wider types unless listed as a fallback).
Inputs fit in the language’s signed 32-bit int range (if you choose a 64-bit fallback, state it explicitly).
We show three methods. Method 2 (bitwise) is compact and avoids overflow on two’s-complement machines with arithmetic right shift (works in Java, Kotlin, Python; on C/C++/Rust it depends on implementation but commonly behaves correctly). Method 3 is a safe fallback using 64-bit arithmetic when available.
Use bitwise identities to compute the average without forming a + b directly. The identity:
avg = (a & b) + ((a ^ b) >> 1)
derives from decomposing a + b = (a & b) * 2 + (a ^ b); dividing by two and using bit operations yields the formula. It avoids overflow because it never forms a + b as a single value.
This formula requires an arithmetic right shift (>>) that preserves the sign bit for negative numbers (Java and Kotlin guarantee arithmetic shift; C/C++/Rust typically perform arithmetic shift on two’s-complement platforms — note the language caveat below).
Caveats: This method relies on two’s-complement representation and an arithmetic right shift. Java/Kotlin/Python/Rust (on typical targets) and mainstream C/C++ compilers on two’s-complement machines make this safe. If you target a platform/language where signed right shift is logical (fills with zero) or two’s-complement is not used, prefer the 64-bit fallback below.
Method 3 — 64-bit (wider-type) fallback (portable and simple)#
If a wider integer type (e.g., 64-bit long/long long) is permitted, promote operands to the wider type, compute the sum safely, then divide and cast back. This is the simplest portable solution if the constraint “use only 32-bit ints” is relaxed.