How to improve this algorithm's efficiency?

Printable View