Optimized loops and implemented statistical calculations