optimising problem 9, now with one less loop