The problem is about larger group sizes: The square root
of Integer.MAX_VALUE
roughly equals 46340.95. Starting from
46341 + 1 we encounter overflow problems:
This can be mitigated by dividing prior to multiplying.
However to avoid integer division truncation we must now
assure selecting the even one of our two factors for
division:
static public int getNumberOfHandshakes(int size) {
if (0 == size % 2) {
// size is even
return size / 2 * (size - 1);
} else {
// size - 1 is even
return (size - 1) / 2 * size;
}
}
Given the square root of 2 *
Integer.MAX_VALUE by ~65535.99998 overflows now happen
when starting from 65536 + 1. This is a
considerable gain in group size limit by ~41% compared to the
current implementation:
Remark: A less elegant but otherwise fully equivalent
solution uses long arithmetics internally:
static public int getNumberOfHandshakes(int size) {
return (int) (size * (size - 1L) / 2);
}