Faster version using pre-computed sums.