Reputation: 3774
What is the running time of the following algorithm in bigO.
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++){
for(int k=j; k<=n;k++){
for(int l=k; l<=n;l++){
...
}
}
}
}
Upvotes: 1
Views: 248
Reputation: 2977
A formula for such a collection of dependent loops, can be inferred like the following:
Where c (constant) is the number of operations inside the innermost loop, n is the number of elements, and r is the number of nested loops.
In the question's case:
Another methodology, efficient but tedious, is to use Sigma notation:
Upvotes: 1
Reputation: 1
my answer is O(N^4)...because there are four "for loops"..and it is easy to judge the runing time of this algo...thanks !
Upvotes: 0
Reputation: 12243
O(N^4) is the cost.
each for nested is N^ so essentially N * N * N * N = N^4
CS610, Algorithm Development, NJIT. My graduate coursework is actually coming in handy.
Upvotes: 0
Reputation: 1576
This algorithm seems to be n^4. Of course, from the theoretical perspective (without any compiler considerations).
Upvotes: 7