zoukankan      html  css  js  c++  java
  • 数论:求逆元的三种模板

    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);
    	}
    }
    
    你将不再是道具,而是成为人如其名的人
  • 相关阅读:
    前端的一些工具
    ubuntu安装intelij idea 和pycharm
    广义欧几里得算法,求解形如ax+by=c的整数解
    Kali安装jdk8
    ARP 项添加失败: 拒绝访问
    Python扩展包,解决”unable to find vcvarsall.bat“
    python实现mschap2
    Ubuntu 安装 Corsaro v2.0.0 全过程
    使用GridFS上传下载图片以及其他文件
    Eclipse设置工作空间编码
  • 原文地址:https://www.cnblogs.com/wsl-lld/p/13393551.html
Copyright © 2011-2022 走看看