文章目录
前言
本文讲述快速幂的原理,以及用法
一、快速幂(Fast Exponentiation)的定义:
定义:快速求,取base为底数的exp次幂,即求:baseexp;
时间复杂度: O(log₂N)
二、快速幂原理:
思想:每一步都把指数分成两半,而相应的底数做平方运算。不仅能把非常大的指数给不断变小,所需要执行的循环次数也变小,而最后表示的结果却一直不会变。
原理:(a* b) % m = ((a % m) * (b % m)) % m
三、常规求幂:
代码块:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll Pow1(ll my_base, ll my_exp) {
ll ans = 1;
for (int i = 1; i <= my_exp; i++) ans *= my_base;
return ans;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); //断开同步流
ll my_base, my_exp, result;
clock_t my_start, my_end;
cin >> my_base >> my_exp;
my_start = clock();
//该函数返回值是硬件滴答数
result = Pow1(my_base, my_exp);
cout << my_base << "^" << my_exp << "=" << result << endl;
my_end = clock();
cout << "time=" << ((double)my_end - my_start) / CLK_TCK << "s" << endl;
//要换算成秒,需要除以CLK_TCK或者 CLK_TCKCLOCKS_PER_SEC
return 0;
}
运行结果:

四、简单快速求幂:
代码块:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll Pow2(ll x, ll y) {
ll ans = 1, base = x;
while (y != 0) {
if (y % 2 != 0) ans *= base;
base *= base;
y /= 2;
}
return ans;
}
int main() {
ios::sync_with_stdio(false)

最低0.47元/天 解锁文章
313





