non recursive solution, but still fast one