Luogu P1226 【模板】快速幂||取余运算 普及-

本文介绍了快速幂算法的核心思想,即通过二进制右移运算减少乘法运算次数,提高计算效率。以计算n的p次方为例,展示了传统计算方法与快速幂算法的区别,以及如何在每一步乘法中取余数。

快速幂的核心思想是用二进制的右移运算来减少运算次数

例如:我们要算 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=nnn3=n2nn4=n3nn5=n4nn6=n5nn7=n6n
运用快速幂,我们可以简化为:
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=nnn4=n2n2n7=n4n2n
可以看出运算次数大量减少了。

其中 7=(111)27=(111)_27=(111)2 对应 n1∗22+1∗21+1∗20n^{1*2^2+1*2^1+1*2^0}n122+121+120
假设 p=(pipi−1...p2p1p0)2p = (p_i p_{i-1}...p_2p_1p_0)_2p=(pipi1...p2p1p0)2, 则 np=npi∗2i+...+p1∗21+p0∗20n^p = n^{p_i*2^i+...+p_1*2^1+p_0*2^0}np=npi2i+...+p121+p020

如果要对结果取余,那么在每一步乘法运算中都要取余,并且还要对最后的结果取余

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值