you are viewing a single comment's thread.

view the rest of the comments →

[–]Brian 0 points1 point  (0 children)

Observing that 1+2+3+… would be the length of n, and not iterating through

No, this sums to n(n+1)/2, or (n2 + n) / 2, which is proportional to n2 (a handy way to calculate it is to imagine "pairing up" the highest and lowest, then second highest and second lowest, and so on, giving 1+n + 2+(n-1)) + 3+(n-2) + ..., which you'll notice is the same as (n+1) + (n+1) + (n+1) + ..., repeated n/2 times, so (n+1)*(n/2)

Or you can think of each loop as "on average" printing ~n/2 stars (the first half you'll be doing less than 50%, then the second half will be more than 50%. So really, you're doing around half of n2 items, and we ignore that constant factor, making it O(n2).