Implement Pow

Implement the function power(b, e), which calculates b raised to the power of e (i.e. be).

Examples:

Input: b = 3.00000, e = 5
Output: 243.00000
Input: b = 0.55000, e = 3
Output: 0.16638
Input: b = -0.67000, e = -7
Output: -16.49971

Constraints:

  • -100.0 < b < 100.0
  • -109 <= e <= 109
  • Either b is not zero or e > 0.
  • -104 <= be <= 104

Approach 01:

class Solution {
  public:
    double power(double b, int e) {
        return pow(b,e);
    }
};
class Solution:
    def power(self, b: float, e: int) -> float:
        return b**e

Time Complexity:

  • Power Function:

    The pow function in the standard library is implemented using exponentiation by squaring, which runs in \( O(\log e) \) time.

  • Overall Time Complexity:

    Since we are directly calling pow, the time complexity is \( O(\log e) \).

Space Complexity:

  • Auxiliary Space:

    The function does not use extra space apart from a few variables, leading to \( O(1) \) space complexity.

  • Overall Space Complexity:

    Thus, the total space complexity is \( O(1) \).

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top