Analytical expression for a sum into two loops

26 Views Asked by At

Is there a way that k can be expressed analytically as a function of i and j for the following sequence

k=0

loop for i=0 until i=N with step + 1
  loop for j=i+1 until j=N with step + 1

k = k + 1

  end j loop
end i loop

So for example if N = 5 the numbers will be

 i                   j                  k

 0                   1                  0
 0                   2                  1
 0                   3                  2
 0                   4                  3
 0                   5                  4

 1                   2                  5
 1                   3                  6
 1                   4                  7
 1                   5                  8

 2                   3                  9
 2                   4                  10
 2                   5                  11

 3                   4                  12
 3                   5                  13

 4                   5                  14

This sequence appears very often in the programs that I am writing and I am wondering whether mathematicians have found an analytical expression for k as:

 k = f(i,j)  

P.S. Or maybe give me a link to somewhere to find more info.

1

There are 1 best solutions below

1
On BEST ANSWER

For all of the $i'<i$, we get a total contribution of the $N$th triangular number minus the $(N-i)$th triangular number: so this is $\frac{N(N+1)}{2} - \frac{(N-i)(N-i+1)}{2}$.

Now for our target $i$, the contribution from the $j$ terms is just $(j-i)$.

Finally, this is shifted by 1 from the numbers you've listed above (are you listing $k$ before the addition happens or something?), so we need to subtract 1.

So the answer should be $k = \frac{N(N+1)}{2} - \frac{(N-i)(N-i+1)}{2} + j -i -1$.