0 votes
What is the time complexity of this program?

for i = 1 to n

    for j = i to n

      for k = j*j to n

         sum++;
in Asymptotic Analysis by AlgoMeister (1.6k points)

5 Answers

+7 votes
 
Best answer

I believe it's O(n2) , and it complies with observed result.

/*******Updated Analysis**********/

As innermost loop only executes on the conditions that i ≦  n0.5 and j ≦ n0.5the original pseudocode can be divided to two parts. 
 

Part 1:
for i = 1 to n0.5

    for j = i to n0.5

      for k = j*j to n 

         sum++;


Part 2:

for i = 1 to n

    for j = n0.5 to n

      for k = j*j to n //will only run once and end loop, hence O(1) 


For the first part 

The innermost loop (sum++) execute on every combination that satisfies 1 ≦ i ≦ j ≦ k0.5 ≦ n0.5

Hence the total count should be something like n0.5 * n0.5 * n giving the time complexity O(n2)

And the second part is clearly O(n2), hence the original algorithm also run at O(n2).

by AlgoMeister (696 points)
selected by
+3 votes

Please provide more information - at least 12 characters

by (216 points)
Good job, TA!
+1 vote
Since the professor suggested that someone try to help prove this programmatically, I've taken the liberty to show that this algorithm runs in O(n^2) time:

public class Algorithm {

    public static void main(String[] args) {
        int sum = 0;
        int n = 100000;

        for (int i = 1; i < n; i++) {
            for (int j = i; j < n; j++) {
                for (int k = j * j; k < n; k++) {
                    sum++;
                }
            }
        }

        System.out.println("complexity: " + sum);
    }
}

Output:

n = 10
sum = 24

n = 100
sum = 2475

n = 1000
sum = 249984

n = 10000
sum = 24997500
by AlgoStar (416 points)
0 votes

Is it simply O(n2.5) ?

by AlgoMeister (648 points)
Ethan, perhaps it may be easier to just run the algorithm on n say 100, 1000 and confirm if your hypothesis matches the observed result?
0 votes
This is my try= O(n^3)

by AlgoMeister (920 points)
Amal, how about simply run this algorithm in your favorite IDE (like Eclipse) and see how the time taken taken for n = 1000  and n = 100 compare.
I'll try it!
The Book: Analysis and Design of Algorithms | Presentations on Slideshare | Lecture Notes, etc
...