3

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?

Moritz Schmidt
  • 2,635
  • 3
  • 27
  • 51
  • 1
    You are aware that your implementation does not save any multiplication compared to the naive implementation `n*n*n*n...*n`? You could if you avoid recalculation of the same powers again and again e.g. by storing them in a shared data-structure. – MrSmith42 Jul 02 '19 at 14:44
  • @MrSmith42 yes I do know that there is no performance gain with this implementation. My goal was only to implement it with a divide and conquer approach since this was the given task. – Moritz Schmidt Jul 02 '19 at 16:03
  • @MrSmith42, if I would store results into memory to look them up later, would this be a dynamic approach? – Moritz Schmidt Jul 02 '19 at 16:13
  • 1
    You could call it dynamic approach. Even if it is a very simple version in this case. – MrSmith42 Jul 03 '19 at 13:43

1 Answers1

4

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).

OmG
  • 18,337
  • 10
  • 57
  • 90