Leetcode 2961. 双模幂运算&&50 Pow(x, n)--快速幂板子

快速幂板子

#include<iostream>
using namespace std;

int n, a, b, p;

long long qmi(int a, int b, int p){
    long long res = 1;
    while(b){
        if(b & 1)   res = (long long) res * a % p;
        b >>= 1;
        a = (long long) a * a % p;
    }
    return res;
}

int main(){
    cin >> n;
    while(n --){
        cin >> a >> b >> p;
        cout << qmi(a, b, p) << endl;
    }
    return 0;
}

 

class Solution {
public:
    vector<int> getGoodIndices(vector<vector<int>>& variables, int target) {
        vector<int> res;
        // 快速幂板子
        auto qmi = [&](int a, int b, int p) -> long long{
            long long ans = 1;
            while (b){
                if (b & 1)  ans = (long long) ans * a % p;
                b >>= 1;
                a = (long long) a * a % p;
            }
            return ans;
        };
        for(int i = 0; i < variables.size(); i ++){
            int a = variables[i][0], b = variables[i][1], c = variables[i][2], m = variables[i][3];
            int t1 = qmi(a, b, 10);
            int t2 = qmi(t1, c, m);
            if(t2 == target)    res.push_back(i);
        }
        return res;
    }
};

 

注意n的范围可能会超出int限制,开成long long

class Solution {
public:
    double myPow(double x, int n) {
        double res = 1;
        bool f = 0;
        long long b = n;
        if (n < 0)   f = 1, b = -b;
        while (b){
            if(b & 1)   res = res * x;
            b >>= 1;
            x = x * x;
        }
        if (f)  return 1 / res;
        return res;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_Ocean__

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

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

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

打赏作者

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

抵扣说明:

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

余额充值