Files
python/TangDou/AcWing/Math/KSM.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

39 lines
1.0 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}