Optimize that dumb algorithm.