finished 2nd algorithm, more efficient