问题
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++;
}
}
回答1:
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:
- The outer loop will run a total of
n
times - The inner loop will run between 1 to
n
times depend on whati
is at the time. But you know that on average this will run(n+1)/2
times. - Thus
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:
- 1 + 2 + 3 + ... + n
So we can do something clever and pair up :
- n with 1: (n + 1) = n + 1
- n-1 with 2: (n - 1) + 2 = n + 1
- n-2 with 3: (n - 2) + 3 = n + 1
- ...
And since we paired these up, we have n/2 such pairs:
- So the sum of 1 + 2 + ... + n is ( (n+1) * (n/2) ).
- So the average is ( (n+1) * (n/2) ) / n = (n+1)/2
(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 =)
回答2:
1
1+2 = 3
1+2+3 = 6
1+2+3+4 = 10
1+2+3+4+5 = 15
It is only me who sees the pattern? :-)
回答3:
Here you go:
count = n * (n + 1) / 2
来源:https://stackoverflow.com/questions/13483512/determining-as-a-function-of-n-how-often-the-statement-incrementing-the-variable