Search code examples
javascripttime-complexitybig-ocomplexity-theory

Number of iterations in compound loop


I am comparing rows to each other just once, so the inner loop decreases in size each iteration:

let num_1 = 0;

for(let i = 0; i < 500; i++){
    for(let j = 0; j < 500; j++){
       num_1++;
    }
}

console.log(num_1); // 500*500 = 250,000


let num_2 = 0;

for(let i = 0; i < 500; i++){
    for(let j = i+1; j < 500; j++){
        num_2++;
    }
}

console.log(num_2); // x*y = 124,750

it looks like x and y are 250 and 499, but not sure why, can anyone explain?


Solution

  • Don't want over-analyze this one, but looks like:

    499+498+497+496+...+1
    

    there are 249 pairs of 500 (499+1, 498+2, 497+3, ...etc)

    and then one odd 250 in the very middle, so the number is:

    249*500 + 250
    

    which doesn't seem to follow Gauss' rule of:

    (start + end) * count / 2 
    

    if someone could reconcile that, that'd be cool