tested algorithm and it works