99HP: working but slow impl of problem 40