0x01位运算

题目链接:a^b

解题思路:

  • 快速幂模版
  • 位运算的应用

常规解法及其问题

  1. 超时:b的上界是 1 9 1^9 19,而1s的范围大约是 1 8 1^8 18,所以在极限条件下,程序会超时
  2. 超过int的范围:如果a足够大,那么 a * a的范围会超过int所能表示的最大范围就 2 32 − 1 2 ^{32} - 1 2321
#include<iostream>
using namespace std;
int main(){
    int a, b, p;
    cin >> a >> b >> p;
    for(int i = 1; i < b ; i++){
        a  = a * a;
    }
    cout << a % p;
    return 0;
}

优化解法:

  • 快速幂:一种计算a^b % p的算法,包含位运算的应用
  • 防止溢出:乘以一个1ll,实现隐式类型转换来实现避免内存的溢出
#include<iostream>
using namespace std;
int main(){
    int a, b, p;
    cin >> a>> b>> p;
    int res = 1 % p;
    while(b){
        if(b & 1){//b的最后一位是1的情况
            res = res * 1ll * a % p;
        }
        a = a * 1ll * a % p;
        b = b >> 1;
    }
    cout << res << endl;
    return 0;
}

题目链接:增加模数

解题思路:

  • 对每一个指数都用快速幂进行计算
  • 快速幂的模版
  • 超时的解决方法:用scanf替代cin,去进行读入操作
#include<iostream>
#include<cstdio>
using namespace std;
int t, m, h;
long long a, b;
int main(){
    scanf("%d", &t);
    while(t--){
        scanf("%d", &m);// 模的数字
        scanf("%d", &h);
        long long res = 0;
        while(h--){//h组数字
            scanf("%d%d", &a, &b);
            long long ans = 1 % m;
            while(b){
                if(b & 1){
                    ans = ans * a % m;
                }
                a = a * a % m;
                b = b >> 1;
            }
            res = (res + ans) % m;
        }
        cout << res <<endl;
    }
    return 0;
}

题目链接:64位整数乘法

#include<iostream>
#include<cstdio>
using namespace std;
typedef unsigned long long ULL;//定义常量 方便使用

ULL a, b, p;
int main(){
    cin >> a >> b >> p;
    ULL res = 0;
    while(b){
        if(b & 1){
            res = (res + a) % p;
        }
        b = b >> 1;
        a = a * 2 % p;// * 2等价于 + a
    }
    cout << res << endl;
    return 0;
}
  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值