逆元 的四种求法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44510468/article/details/102760098

定义法

const ll mod = 1e9+7;
for ( ll i = 1; i < 1e10; ++i ) {
    if ( 2*i%mod==1 ) {
        cout << i << endl;
        break;
    }
}

费马小定理+快速幂

在这里插入图片描述
逆元公式如下, 再将费马小定理带入, 即可解得 a 的逆元 x ( 这里需要特别注意 这个 模一定要是 质数 !!! )

在这里插入图片描述

#include <bits/stdc++.h> 
using namespace std; 
typedef long long ll;
const ll mod = 1e9+7;
ll qpow ( ll base, ll n, ll mod ) {
    ll ans = 1;
    while ( n ) {
        if ( n&1 ) ans = ans*base%mod;
        base = base*base%mod;
        n >>= 1;
    }
    return ans;
}
int main ( ) { 
    cout << qpow( 2, mod-2, mod ) << endl;
    return 0 ; 
} 

扩展欧几里得

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 1e9+7;
ll inv ( ll a ) {
    if( a==1 ) return 1;
    return inv(mod%a)*(mod-mod/a)%mod;
}
int main ( ) {
    cout << inv( 2 ) << endl;
    return 0;
}

线性打表求逆元

    const ll mod = 1e9+7;
    map<ll,ll> inv;
    inv[1] = 1;
    for ( ll i = 2; i <= 1e10; ++i ) inv[i] = (mod-mod/i)*inv[mod%i]%mod; 

    cout << inv[2] << endl;

猜你喜欢

转载自blog.csdn.net/weixin_44510468/article/details/102760098