I'm new here so cut my some slack and let me know if my question can have any improvements.
So me and a friend are at a bit of a disagreement on an algorithm's complexity. He seems to be certain that the algorithm has a big O notation of O(n^2) but I just think its O(n)
Can we have some pointers, to hopefully end our argument ha!
The Algorithm:
Input: Matrix M[1..n][1..n]
Output: boolean true if M is lower triangular
begin isLowerTriangular(Matrix[][] M, size n)
for i:=1 to n-1 loop
for j:=i+1 to n loop
if M[i][j] != 0
return false
return true
end isLowerTriangular
1 Answer 1
It's O(n^2).
for i:=1 to n-1 loop
for j:=i+1 to n loop
operation()
done
done
So, for i = 1, the second loop is executed n times, for i = 2 it is executed n-1 times, etc..
This gives the sum n + n-1 + n-2 + ... + 1
The formula which gives the number of operation()
ran is n*(n+1)/2
or (n^2 + n)/2
.
Thus, it's O(n^2)
EDIT:
Get the formula
The trick to get the result is to add what I call the reverse sum, that is the same sum in reverse order. Here is how it works:
We want to compute 1 + 2 + 3 + ... + n-2 + n-1 + n
For this, we add n + n-1 + n-2 + ... + 3 + 2 + 1
(we remember that we have to divide by two after).
We pair the operands of those two sums now:
1 + 2 + 3 + ... + n-2 + n-1 + n
+ n + n-1 + n-2 + ... + 3 + 2 + 1
= n+1 + n+1 + n+1 + ... + n+1 + n+1 + n+1
= n * n+1
To get this, we just added together 1 and n, then 2 and n-1, ...
Remember that we have to divide by 2, and we get the final result:
1 + 2 + 3 + ... + n-2 + n-1 + n = (n * n+1)/2
n*(n-1)/2
n
. So ifi+1=2
andn=100
it will iterate98
times