• 数论:求逆元的三种模板


    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);
    	}
    }
    
    你将不再是道具,而是成为人如其名的人
  • 相关阅读:
    自考新教材-p240_2
    自考新教材-p243_5_(1)
    自考新教材-p242_4
    自考新教材-p233
    自考新教材-p230
    Spring入门(9)-AOP初探
    MongoDB的备份与恢复
    JVM基础知识(1)-JVM内存区域与内存溢出
    Spring入门(8)-基于Java配置而不是XML
    Spring入门(7)-自动检测Bean
  • 原文地址:https://www.cnblogs.com/wsl-lld/p/13393551.html
Copyright © 2020-2023  润新知