c++递归函数求x的n次方
时间: 2023-09-12 13:10:14 浏览: 77
以下是递归函数求x的n次方的Python代码:
```python
def power(x, n):
if n == 0:
return 1
elif n % 2 == 0:
return power(x * x, n // 2)
else:
return x * power(x * x, (n - 1) // 2)
```
这个函数首先检查n是否为0,如果是,则返回1。否则,它检查n是否为偶数,如果是,则将x的平方的n/2次方作为结果递归调用power函数。如果n是奇数,则将x乘以x的平方的(n-1)/2次方作为结果递归调用power函数。这个算法的时间复杂度为O(log n)。
相关问题
c++递归代码求x的n次方
以下是计算x的n次方的C++递归代码:
```c++
#include <iostream>
using namespace std;
double power(double x, int n) {
if (n == 0) {
return 1.0;
}
if (n < 0) {
return 1 / power(x, -n);
}
double half = power(x, n / 2);
if (n % 2 == 0) {
return half * half;
} else {
return half * half * x;
}
}
int main() {
double x;
int n;
cout << "请输入x和n:" << endl;
cin >> x >> n;
cout << x << "的" << n << "次方是:" << power(x, n) << endl;
return 0;
}
```
该递归函数与前面提供的非递归函数的思路相同,使用快速幂算法计算x的n次方,但是使用递归实现。在处理负数幂时,直接返回1/power(x, -n)即可。
c++代码求x的n次方
以下是计算x的n次方的C++代码:
```c++
#include <iostream>
using namespace std;
double power(double x, int n) {
if (n == 0) {
return 1.0;
}
if (n < 0) {
n = -n;
x = 1 / x;
}
double half = power(x, n / 2);
if (n % 2 == 0) {
return half * half;
} else {
return half * half * x;
}
}
int main() {
double x;
int n;
cout << "请输入x和n:" << endl;
cin >> x >> n;
cout << x << "的" << n << "次方是:" << power(x, n) << endl;
return 0;
}
```
用户输入x和n,然后调用power函数计算x的n次方,最后输出结果。该函数使用递归实现快速幂算法,时间复杂度为O(log n)。为了处理负数幂,如果n为负数,将n取相反数,并将x变为1/x。
相关推荐
![md](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)