optimize with while loops