数论:求逆元的三种模板
1.线性求逆元
点击查看折叠代码块
typedef long long ll
int n;
int mode;
ll inv[maxn];
void init(int mode){//线性求逆元
inv[0]=inv[1]=1;
for (int i=2;i<maxn;i++){
inv[i] = ((mode-mode/i)*inv[mode % i]) % mode;
}
}
2.费马小定理,快速幂求逆元
点击查看折叠代码块
ll mypow(ll a,ll b){//快速幂
ll ret=1;
while(b){
if(b&1){
ret=ret*a%mode;
}
a=a*a%mode;
b>>=1;
}
return ret;
}
ll C_inv(ll x){//快速幂——费马小定理求逆元
return mypow(x,mode-2);
}
3.扩展欧几里得求逆元
点击查看折叠代码块
void gcd(ll a,ll b,ll &d,ll &x,ll &y) {
if(!b) { d=a; x=1; y=0;}
else {gcd(b,a%b,d,y,x); y -= x*(a/b);}
}
ll gcd_inv(ll a,ll n) {//扩展欧几里得求逆元
ll d,x,y;
gcd(a,n,d,x,y);
return d == 1 ? (x+n) % n : -1;
}
4.java版高精求快速幂和逆元:
点击查看代码块
import java.math.*;
import java.util.*;
public class Main{
static BigInteger a,b;
static BigInteger Mod = BigInteger.valueOf(19260817);
static BigInteger mypow(BigInteger a,BigInteger b) {
BigInteger ret = BigInteger.valueOf(1);
while(0 != b.compareTo(BigInteger.valueOf(0))) {
if(0 == b.mod(BigInteger.valueOf(2)).compareTo(BigInteger.valueOf(1))){
ret = ret.multiply(a).mod(Mod);
}
a = a.multiply(a).mod(Mod);
b=b.divide(BigInteger.valueOf(2));
}
return ret;
}
static BigInteger inv(BigInteger x) {
BigInteger Inv = mypow(x,Mod.subtract(BigInteger.valueOf(2)));
return Inv;
}
public static void main(String[] args) {
Scanner cin = new Scanner (System.in);
a=cin.nextBigInteger();
b=cin.nextBigInteger();
BigInteger ans = a.multiply(inv(b)).mod(Mod);
System.out.println(ans);
}
}