Naive solution for exercise 28, very slow for n > 30