Search code examples
algorithmmathbig-ocomputer-scienceinteger-arithmetic

first and last terms of a nested loop, sums of arithmetic series starting with non zero index


I have 2 arithmetic series...

(i) for i<- 1 to n do
 for j<- 1 to 2n-i do
//a unit cost operation

So the first term is 2n-1, last term is 2n-n = n

(ii) for i <- 1 to n do
 for j <- 2 to (n+i) do
// a unit cost operation

So similarly, is the first term n+1-1 = n, last term n+n-1 = 2n-1 ?

Where does the minus 1 above come from ? Is this because the index starts with 2 ?


Solution

  • Edit: Your previous question shows that you are interested in the number of terms in the inner summation. The loop for j<- first to last has last-first+1 terms (this is easiest to see if you write down some examples with small last-first). So for (1), there are (2n-i)-(1)+1=2n-i terms for each i. For (2), there are (n+i)-(2)+1=n+i-1 terms for each i.


    You add according to the limits that the series specify themselves:

    1. when i=1, for j<- 1 to 2n-1
      when i=2, for j<- 1 to 2n-2
      . . .
      when i=n, for j<- 1 to 2n-n

    2. when i=1, for j<- 2 to n+1
      when i=2, for j<- 2 to n+2
      . . .
      when i=n, for j<- 2 to n+n