Rewrite recursion in terms of loops; make it a bit faster