You don't need to loop till i but even i/2 or square root of i is also sufficient.