# Pow(x, n)

> Implement [pow(x,n)](http://www.cplusplus.com/reference/valarray/pow/)

## Thoughts

分治，比如2^9分成2^4 \* 2^4 \* 2，2^4再分成2^2\*2^2直到n == 1。n是奇数时还有个额外的x要乘，n为负数时用且n为奇数时做额外除x。n为INT\_MIN时可能导致的 \*溢出问题，因此不建议当n < 0时让n = -n, x = 1/ x的方法，而是直接让pow(x / 2) / x 比较好。

## Code

```cpp
/*
 * @lc app=leetcode id=50 lang=cpp
 *
 * [50] Pow(x, n)
 */
class Solution {
public:
    double myPow(double x, int n) {
        if (n == 0) return 1;
        double res = myPow(x, n / 2);
        res *= res;
        if (n % 2 == 0) return res;
        if (n < 0) return res / x;
        return res * x;
    }
};


```

## Analysis

Errors:\
1\. n = min\_value溢出

时间复杂度O(lgN), 空间O(1).


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hao-fu-1.gitbook.io/oj/math/powx-n.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
