快速幂c++递归算法
时间: 2023-11-18 13:52:54 浏览: 47
好的,以下是快速幂c++递归算法的代码:
```c++
long long quickPow(long long a, long long b) {
if (b == 0) return 1;
long long res = quickPow(a, b / 2);
if (b % 2 == 0) return res * res;
else return res * res * a;
}
```
其中,a为底数,b为指数。该算法的时间复杂度为O(logn)。
相关问题
c++递归算法
递归算法是一种重要的算法思想,它通过将问题分解成更小的子问题来解决复杂问题。在 C++ 中,递归算法的实现通常使用函数调用来实现。以下是一个示例代码,使用递归算法实现斐波那契数列:
```c++
#include <iostream>
using namespace std;
int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
int main() {
int n = 10;
cout << "Fibonacci sequence of " << n << " terms:" << endl;
for (int i = 0; i < n; i++) {
cout << fibonacci(i) << " ";
}
cout << endl;
return 0;
}
```
在上面的代码中,`fibonacci(int n)` 函数使用递归算法实现了斐波那契数列的计算。当 `n <= 1` 时,返回 `n`,否则返回 `fibonacci(n - 1) + fibonacci(n - 2)`。在 `main()` 函数中,我们调用 `fibonacci()` 函数计算斐波那契数列并输出结果。
需要注意的是,递归算法可能会导致函数的调用栈溢出,因此在使用递归算法时需要谨慎,尤其是在处理大数据量的情况下。
c++递归算法求阶乘
C++递归算法求阶乘的实现如下:
```cpp
#include <iostream>
int factorial(int n) {
// 基线条件,当n为0或1时,直接返回1
if (n == 0 || n == 1) {
return 1;
}
// 递归调用,将问题规模缩小,求解n-1的阶乘
return n * factorial(n - 1);
}
int main() {
int n;
std::cout << "请输入一个非负整数:";
std::cin >> n;
std::cout << n << "的阶乘是:" << factorial(n) << std::endl;
return 0;
}
```
以上代码中,`factorial`函数使用递归的方式来求解阶乘。当输入的n为0或1时,直接返回1作为基线条件。否则,递归调用`factorial`函数来求解n-1的阶乘,并将结果与n相乘返回。