Rewrote the second algorithm without recursion