Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithmic order of growth of the code

I am attending a course online and stuck at the following question. What is the order of growth of the worst case running time of the following code fragment as a function of N?

int sum = 0;
for (int i = 1; i <= N*N; i++)
    for (int j = 1; j <= i; j++)
        for (int k = 1; k <= j; k++)
            sum++;

I thought that it is of the order of N^4 but it seems this answer is wrong. can you please explain?

like image 783
Ankit Kumar Avatar asked Mar 05 '14 08:03

Ankit Kumar


People also ask

How do you find the order of growth code?

We say that R(n) has order of growth Θ(f (n)), written R(n) = Θ(f (n)) (pronounced “theta of f (n)”), if there are positive constants k1 and k2 independent of n such that k1 f (n) ≤ R(n) ≤ k2 f (n) for any sufficiently large value of n.

What is the order of growth of functions?

An order of growth is a set of functions whose asymptotic growth behavior is considered equivalent. For example, 2n, 100n and n+1 belong to the same order of growth, which is written O(n) in Big-Oh notation and often called linear because every function in the set grows linearly with n.

What does the order of an algorithm mean?

The order of an algorithm is essentially a measure of its efficiency, specifically in the worst-case scenario. An algorithm may take many inputs (in the case of a sorting algorithm, we only need one — an array), and it's order will depend on both the nature of the size of these inputs.

What is order of growth in Java?

Solution: In theory, the order of growth is n log log n. Follows from Mertens' theorem in number theory. In practice, a log log n factor may be hard to identify.


1 Answers

It is of order O(N^6). You should note that it is not true that every loop simply add an order N to the complexity. Considering the following example:

int sum = 0;
for (int i = 1; i <= M; i++)
    for (int j = 1; j <= i; j++)
        for (int k = 1; k <= j; k++)
            sum++;

You should be able to figure out it is of order O(M^3) easily, so if you replace M=N^2, then you will get the answer. The key point is that every inner loop are of order O(N^2) in this case, but not O(N).

like image 185
unsym Avatar answered Oct 18 '22 14:10

unsym