Fix overflow in integer calculations (#4970)