Q5 solution converted from erlang