Implement algorithm with while loop instead of recursion