Replace a recursion with a loop for speed.