Improve the efficiency of the code 

From N^4 to N^2 for intermediate data size
Merge pull request #8 from luborliu/patch-3

Improve the efficiency of the code