Implemented second algorithm