optimization for n<=1000 completed