快速幂与64位整数乘法(位运算)

矩阵快速幂和64位整数乘法

矩阵快速幂

问题链接: AcWing 90. 64位整数乘法
问题描述:
在这里插入图片描述
分析
快速幂需要用到位运算的思想,求 a b a^b ab,我们将 b b b转换成二进制的形式,假设 b = 7 b=7 b=7,那么 a 7 = a ( 111 ) 2 = a 2 0 + 2 1 + 2 2 = a ∗ a 2 ∗ a 4 a^7=a^{(111)_2}=a^{2^0+2^1+2^2}=a*a^2*a^4 a7=a(111)2=a20+21+22=aa2a4
代码如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;

ll ksm(ll a,ll b,ll p){
    ll res=1;
    while(b){
        if(b&1) res=res*a%p;
        b>>=1;
        a=a*a%p;
    }
    return res%p;
}

int main(){
    int n;
    cin>>n;
    while(n--){
        int a,b,p;
        scanf("%d%d%d",&a,&b,&p);
        printf("%lld\n",ksm(a,b,p));
    }
    return 0;
}

64位整数乘法

问题链接: AcWing 90. 64位整数乘法
问题描述
在这里插入图片描述
分析
大数乘法与快速幂的思想类似,都需要转化为位运算, a ∗ b a*b ab假设 b = 7 = ( 111 ) 2 b=7=(111)_2 b=7=(111)2 那么 a ∗ 7 = a ∗ ( 111 ) 2 = a ∗ ( 2 0 + 2 1 + 2 2 ) = a + a 2 + a 4 那么 a*7=a*{(111)_2}=a*(2^0+2^1+2^2)=a+a^2+a^4 那么a7=a(111)2=a(20+21+22)=a+a2+a4

代码如下:

#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
ll ksm(ll a,ll b,ll p){
     ll res=0;
     while(b){
         if(b&1) res=(res+a)%p;
         a=2*a%p;
         b>>=1;
     }
     return res%p;
}
int main(){
    ll a,b,p;
    cin>>a>>b>>p;
    cout<<ksm(a,b,p);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chp的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值