modified algorithm to hold sum rather than computing it each time