Fixed calculation of number of iterations for loops