Merge three loops over a range into one loop