Faster implementation of sum

This is re-submitted. I have made modifications based on Steven's comments.