The way the items are ordered now you can see that each of those pairs is equal to N (N11 is N, N22 is N) Since there are N1 items, there are (N1)/2 such pairs So you're adding N (N1)/2 times, so the total value is N*(N1)/2