Optimize pth-trapezoidal loop