Number of iterations in nested loops?

So, I looked at this code from the tutorial:

for (int i=0; i<N; i++)
   for(int j=i+1; j<N; j++)

The author stated that the internal for-loop iteration is performed exactly N * (N-1) / 2 times, but does not give grounds for how he arrived at this equation. I understand N * (N-1), but why divide by 2? I ran the code myself and, of course, when N is 10, the inner loop repeats 45 times (10 * 9/2).

I messed up the code myself and tried the following (assigned only ij):

for (int i=0; i<N; i++)
   for(int j=i; j<N; j++)

At N = 10, this leads to 55. Thus, it is difficult for me to understand basic math here. Of course, I could just connect all the values โ€‹โ€‹and make my way through the problem, but I feel that there is something substantial and very simple that I am missing. How would you come up with an equation to describe the for loop I just built? Is there a way to do this without relying on exits? Thank you for your help!

+3
source share
4 answers

, , . i == 0, 1 N-1, N-1 . i 1, 2 N-1, N-2 . : N-3 , , N-4 .. , i == N-1, j = N . , .

- :

(N-1) + (N-2) + (N-3) + ... + 1 + 0

-, 1 N-1. (N-1) - , Wikipedia , , n- n (n + 1)/2. (N-1) th , , n=N-1,

(N-1)(N-1+1)/2 = N(N-1)/2
+9

, N , (N-1). 1 + 2 + 3 +....

N * (N+1) / 2 "" . , , : 1 100. , , : 5050. : 1 + 100; 2 + 99; 3 + 98; 4 + 97; .. 50 + 51. 50 101 . , (100/2) * (100 + 1); /2.

, (N-1) (N + 1), 1, 0, , .

+6

, int (j) i. N = 10, (i) 10 , j- 0, 1, 2, 3, 4, 5, 6, 7, 8 9 . , , . 0 N-1 N (N-1)/2. 1 N.

, 1 + 2 + 3 +... + n = n * (n + 1)/2

Sum from 1 to N

+3

, :

1 2 3 4 5 6 7 8 9 10

, "" :

0 1 2 3 4 
9 8 7 6 5

, , 9 (N-1), 5 (N/2) . , N N/2 , (N-1). , , (N/2) (N-1), ( ) N (N-1)/2.

, "" , . "0", , . , N = 9 N = 10. :

1 2 3 4
8 7 6 5

This gives us (N-1) / 2 columns (9-1 = 8, 8/2 = 4), each of which adds up to N, so the sum will be N * (N-1) / 2. Despite the fact that we came to this in a slightly different way, this is an exact match for the formula above when N is equal. Again, it seems pretty obvious that this will remain true regardless of the number of columns used (i.e. the total number of iterations).

For any N (odd or even), the sum of numbers from 0 to N-1 is N * (N-1) / 2.

0
source

Source: https://habr.com/ru/post/1753403/