You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
1.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
int normal_pow(int a, int p) {
int ans = pow(a, p); //普通幂
return ans;
}
//递归版本的快速幂
int qpow_1(int a, int p) {
if (p == 0)
return 1; //任何数的0次方都是1,递归出口
else if (p & 1) //如果p是奇数
return qpow_1(a, p - 1) * a; //结果=qpow_1(a,p-1)*a相当于用小一级的数字进行描述形成递归
else {
int t = qpow_1(a, p / 2); //如果p是偶数,分治,结果相乘
return t * t;
}
}
//循环版本的快速幂,利用二进制思想进行8 4 2 1方式计算达到logN的时间复杂度
int qpow_2(int a, int p) {
int ans = 1;
while (p) {
if (p & 1) ans *= a;
a *= a;
p >>= 1; //缩小一半
}
return ans;
}
int main() {
for (int i = 1; i <= 10; i++) {
cout << normal_pow(2, i) << endl;
cout << qpow_1(2, i) << endl;
cout << qpow_2(2, i) << endl;
}
return 0;
}