Why is the time complexity of 2 for loops not O(n*2^n)?

Peter :

The time complexity for this method is O(2^n) according to my prof.

I feel that the time complexity for this method should be O(n * 2^n) because

The outer for loop cost O(n)

The inner for loop cost O(2^n)

public static int loop(int n) {
    int j = 1;
    for (int i = 0; i < n; i++) {
        for (int k = j; k > 0; k--) {
            System.out.println("Hello world");
        }
        j *= 2;
    }
    return j;
}
SomeDude :

Consider this:

For i = 0 : j = 1 -> 2^0

For i = 1 : j = 2 -> 2^1

For i = 2 : j = 4 -> 2^2

For i = 3 : j = 8 -> 2^3 ....

For i = n-1 : j = 2^n-1

If you add all of those :

2^0 + 2^1 + 2^2 +.....+2^(n-1) => order of 2^(n) -> 2^(n) - 1 to be precise

So the time complexity is O(2^n)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=28537&siteId=1