快速幂算法求解逆元

103 阅读1分钟

#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_map>
using namespace std;

typedef long long LL;
const LL mod = 1e9 +7;

// 快速幂算法,计算 base^power mod modulo 的值
LL fast_power(LL base, LL power, LL modulo) {
    LL result = 1;
    while (power > 0) {
        if (power & 1) {
            result = (result * base) % modulo;
        }
        base = (base * base) % modulo;
        power >>= 1;
    }
    return result;
}

// 使用快速幂算法求解 a 在模 mod 意义下的逆元
LL modular_inverse(LL a, LL mod) {
    LL inverse = fast_power(a, mod - 2, mod);
    if ((a * inverse) % mod != 1) {
        return -1;  // a 没有逆元
    } else {
        return inverse;  // 返回 a 在模 mod 意义下的逆元
    }
}