Optimize the cartesian recursive function.