简体   繁体   中英

How to find the number of multiplications for x^63 using the exponent recursive function and how to justify it?

How would I go about justifying this algorithm is O(log n)?

public static long exponentiation(long x, int n){

    if(n == 0){
        return 1;
    }
    else if (n % 2 == 0){
        x = exponentiation(x, n / 2);
        return x * x; 
    }
    else{
        return x * exponentiation(x, n-1);
    }
}

Each recursive call to method exponentiation is a multiplication step . Hence you need to count the number of recursive calls. There are several ways to achieve this. I chose to add another parameter to the method.

public static long exponentiation(long x, int n, int count) {
    if (n == 0) {
        System.out.println("steps = " + count);
        return 1;
    }
    else if (n % 2 == 0) {
        x = exponentiation(x, n / 2, count + 1);
        return x * x; 
    }
    else {
        return x * exponentiation(x, n - 1, count + 1);
    }
}

Here is the initial call to method exponentiation

exponentiation(2, 63, 0);

When I run the above code, the following is printed

steps = 11

You can use a static counter as well (without changing the prototype of the function):

public static long counter = 0;

public static long exponentiation(long x, int n){
    if(n == 0){
        return 1;
    }
    else if (n % 2 == 0){
        x = exponentiation(x, n / 2);
        counter++;
        return x * x; 
    }
    else{
        counter++;
        return x * exponentiation(x, n-1);
    }
}

However, you need to reset the counter before calling the function each time, ie, set counter = 0 .

Theoretical Analysis

Note that you need to the counter to prove that it is in O(log(n)) . To prove the complexity, just you need to find the complexity term by looking at the flow of the code. Suppose T(n) is the number of multiplications for computing x^n . So, based on the written code, T(n) = T(n/2) + 1 , if n is even, and T(n) = T(n-1) + 1 , if n is odd. Now, at least in one of two consecutive recursions, input n is even. Therefore, at most 2 log(n) is required to reach to n = 0 . Because, for each even input, the next input will be halved. So, we can conclude that the algorithm is in O(log(n)) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM