逆元【模板】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013852115/article/details/82902009

参考:https://blog.csdn.net/baidu_35643793/article/details/75268911

费马小定理求逆元 O(logn):

const int mod = 1000000009;
long long quickpow(long long a, long long b) {
    if (b < 0) return 0;
    long long ret = 1;
    a %= mod;
    while(b) {
        if (b & 1) ret = (ret * a) % mod;
        b >>= 1;
        a = (a * a) % mod;
    }
    return ret;
}
long long inv(long long a) {
    return quickpow(a, mod - 2);
}

逆元线性筛 O(n):

const int mod = 1000000009;
const int maxn = 10005;
int inv[maxn];
inv[1] = 1;
for(int i = 2; i < 10000; i++)
    inv[i] = inv[mod % i] * (mod - mod / i) % mod;

阶乘的逆元 O(logn+n):

inv[maxn]=mod_pow(fac[maxn],mod-2);
for(ll i=maxn-1;i>=0;i--)
    inv[i]=(inv[i+1]*(i+1))%mod;

猜你喜欢

转载自blog.csdn.net/u013852115/article/details/82902009