快速幂的核心思想是用二进制的右移运算来减少运算次数
例如:我们要算 npn^pnp 假设 p=7p=7p=7,我们原来的运算步骤是:
n2=n∗nn3=n2∗nn4=n3∗nn5=n4∗nn6=n5∗nn7=n6∗n
n^2 = n * n\\
n^3 = n^2 * n\\
n^4 = n^3 * n\\
n^5 = n^4 * n\\
n^6 = n^5 * n\\
n^7 = n^6 * n\\
n2=n∗nn3=n2∗nn4=n3∗nn5=n4∗nn6=n5∗nn7=n6∗n
运用快速幂,我们可以简化为:
n2=n∗nn4=n2∗n2n7=n4∗n2∗n
n^2 = n * n\\
n^4 = n^2 *n^2\\
n^7 = n^4 * n^2 * n\\
n2=n∗nn4=n2∗n2n7=n4∗n2∗n
可以看出运算次数大量减少了。
其中 7=(111)27=(111)_27=(111)2 对应 n1∗22+1∗21+1∗20n^{1*2^2+1*2^1+1*2^0}n1∗22+1∗21+1∗20。
假设 p=(pipi−1...p2p1p0)2p = (p_i p_{i-1}...p_2p_1p_0)_2p=(pipi−1...p2p1p0)2, 则 np=npi∗2i+...+p1∗21+p0∗20n^p = n^{p_i*2^i+...+p_1*2^1+p_0*2^0}np=npi∗2i+...+p1∗21+p0∗20
如果要对结果取余,那么在每一步乘法运算中都要取余,并且还要对最后的结果取余。
AC代码
#include <iostream>
using namespace std;
using LL = long long;
LL binpowmod(LL a, LL b, LL mod)
{
LL res = 1;
a %= mod;
while (b > 0) {
if (b & 1) {
res = (res * a) % mod;
}
a = (a * a) % mod;
b >>= 1;
}
return res % mod;
}
int main()
{
LL a, b, mod;
cin >> a >> b >> mod;
LL res = binpowmod(a, b, mod);
cout << a << "^" << b << " mod " << mod << "=" << res << endl;
return 0;
}
本文介绍了快速幂算法的核心思想,即通过二进制右移运算减少乘法运算次数,提高计算效率。以计算n的p次方为例,展示了传统计算方法与快速幂算法的区别,以及如何在每一步乘法中取余数。

被折叠的 条评论
为什么被折叠?



