implemented second algorithm