Java program to calculate the power of a number | exponential (m^n)

 // Time Complexity O(n) and Space Complexity O(n)

int pow_recursive(int m, int n) {

    if(n == 0) {

        return 1;

    }

    return pow_recursive(m, n - 1) * m;

}

// Time Complexity O(n/2) and Space Complexity O(n)

int pow_recursive_improved(int m, int n) {

    if(n < 0) {

       return 0;

    }

    if(n == 0) {

        return 1;

    }

    if(n % 2 == 0) { // Even

        return pow_recursive_improved(m*m, n/2);

    }

    return m * pow_recursive(m*m, (n - 1) / 2);

}

// Time Complexity O(n) and Space Complexity O(1)

int pow_iterative(int m, int n) {

    if(n < 0) {

        return 0;

    }

    if(n == 0) {

        return 1;

    }

    int result = 1;

    for(int i = 0; i < n; i++) {

       result *= m;

    }

    return result;

}

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance