Problem 18 non-brute force