Returning to a problem after 3 years. This is slightly optimized brute-force and can be much quicker.