You can limit the length of m, and initial ok before for, it can speed up the time. But I don't know how to reduce the memory, do you have any idea ?