So I was looking at this code from a textbook:
for (int i=0; i<N; i++)
for(int j=i+1; j<N; j++)
The author stated that the inner for-loop iterates for exactly N*(N-1)/2 times but gives no basis for how he arrived to such an equation. I understand N*(N-1) but why divide by 2? I ran the code myself and sure enough when N is 10, the inner loop iterates 45 times (10*9/2).
I messed around with the code myself and tried the following (assigned only i to j):
for (int i=0; i<N; i++)
for(int j=i; j<N; j++)
With N = 10, this results in 55. So I’m having trouble understanding the underlying math here. Sure I could just plug in all the values and bruteforce my way through the problem, but I feel there is something essential and very simple I’m missing. How would you come up with an equation for describing the for loop I just constructed? Is there a way to do it without relying on the outputs? Would really appreciate any help thanks!
Think about what happens each time the outer loop iterates. The first time,
i == 0, so the inner loop starts at1and runs toN-1, which isN-1iterations in total. The next time through the outer loop,ihas incremented to1, so the inner loop starts at2and runs up toN-1, for a total ofN-2iterations. And that pattern continues: the third time through the outer loop, you getN-3iterations, the fourth time through,N-4, etc. When you get to the last iteration of the outer loop,i == N-1, so the inner loop starts withj = Nand stops immediately. So that’s zero iterations.The total number of iterations is the sum of all these numbers:
To look at it another way, this is just the sum of the positive integers from
1toN-1. The result of this sum is called the (N-1)th triangular number, and Wikipedia explains how you can find that the formula for the n’th triangular number is n(n+1)/2. But here you have the (N-1)th triangular number, so if you setn=N-1, you get