Ok so I’m new to analyzing algorithms and would really appreciate any helpful tips that can be shared on how to go about this. I am trying to determine how many times count is incremented as a function of n. I have ran it in an ide and for values 1-7 the output is 1,3,6,10,15,21,28. Im just unsure how to write this as a function of n? Thanks.
The loop is as follows:
for(int i = 1 ; i <= n ; i++){
for (int j = 1 ; j <= i ; j++) {
count++;
}
}
The aim of this type of exercise is to teach how to you analyze it on paper instead of running it on a machine. But let’s look at the pattern:
ntimesntimes depend on whatiis at the time. But you know that on average this will run(n+1)/2times.count = n(n+1)/2), which isO(n^2)See arithmetic series
Update: As requested – why the inner loop is
(n+1)/2:The outer loop will increment i between 1 and n. So on each iteration of the outer loop, the inner loop will “loop” one more than than it did previously.
Thus the inner loop will iterate this number of times:
So we can do something clever and pair up :
And since we paired these up, we have n/2 such pairs:
(Visualize it as you are writing 1 + 2 + 3 + … + n on a long strip of paper, and you fold it in half.)
I would also highly recommend reading this famous story about Karl Friedrich Gauss so you’ll always remember how to sum arithmetic series =)