快速幂
1.计算幂
- 通常的方法是写一个函数或调用
pow() 函数
#include <bits/stdc++.h>
using namespace std;
void faction(int n, int power) {
int ans = 1;
for (int i = 1; i <= power; i ++) ans *= n;
printf("%d", ans);
}
int main() {
int A, B scanf("%d %d", &A, &B);
faction(A, B); //pow(A, B);
return 0;
}
但是这种方法的时间复杂度是
2.快速幂引入
它是一种常见的方法,它可以将指数进行折半处理,因此它的时间复杂度为
3.快速幂
核心:利用二进制进行快速运算
例如
运用初中数学知识得到:
∵
∴
有发现它正好是 1110(2) 非零位的项,只需要将它们累加起来就好。最后发现了这个式子:
所以代码就出来了
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll faction(int a, int b)
{
ll ans = 1;
while (b > 0)
{
if (b & 1) ans *= a;
a *= a;
b >>= 1;
}
printf("%lld", ans);
}
int main() {
ll a, b; scanf("%lld %lld", &a, &b);
faction(a, b);
return 0;
}