algorithmruntimedivide-and-conquermaster-theorem

Divide and Conquer to solve the power of a number, runtime analysis with master theorem


I implemented a divide and conquer algorithm to calculate the power of a number:

public static void main(String[] args) {
    System.out.println("Result: " + pow(2, 1));
    System.out.println("Result: " + pow(2, 9));
    System.out.println("Result: " + pow(2, 8));
    System.out.println("Result: " + pow(2, 0));
}

private static int pow(int n, int pow) {
    if(pow == 0) {
        return 1;
    }

    if(pow > 2) {
        int leftPow;
        int rightPow;

        if(pow % 2 != 0) {
            leftPow = pow/2;
            rightPow = pow/2+1;
        } else {
            leftPow = pow/2;
            rightPow = leftPow;
        }

        return pow(n, leftPow) * pow(n, rightPow);
    } else {
        if(pow == 1) {
            return n;
        } else {
            return n * n;
        }
    }
}

My method seems to work, since the output is:

Result: 2
Result: 512
Result: 256
Result: 1

Now Iam trying to determine the runtime of my algorithm using the Master-Theorem:

I assume, that

, since the recursive call appears two times,

, since Iam creating two subproblems out of one problem

and , since combining the results takes constant time.

The watershed constant () should be .

With these values, I assume that the first rule of the Theorem holds: , with , since .

Therefore the runtime should be: .

Iam quite unsure about this result, since I never had the case .

Is my analysis correct?


Solution

  • First, you should notice that the complexity will be explained based on the pow. So, n in your analysis means pow not n variable in your program.

    Second, as the number of computations such as comparison and multiplying is constant (less than 10 for your program), so f(n) = \Theta(1) and you can write it f(n) = 1 here.

    Therefore, the complexity is T(n) = 2T(n/2) + 1 (you can see Akra-Bazzi method too), and T(n) = \Theta(n).