math: check for overflows when calculating the max