Alternative solution for problem 47 (way faster)