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);
    	}
    }
    
    你将不再是道具,而是成为人如其名的人
  • 相关阅读:
    【转】CUDA5/CentOS6.4
    【转】centos 6.4 samba 安装配置
    【转】Install MATLAB 2013a on CentOS 6.4 x64 with mode silent
    【转】Getting xrdp to work on CentOS 6.4
    【VLFeat】使用matlab版本计算HOG
    Unofficial Windows Binaries for Python Extension Packages
    March 06th, 2018 Week 10th Tuesday
    March 05th, 2018 Week 10th Monday
    March 04th, 2018 Week 10th Sunday
    March 03rd, 2018 Week 9th Saturday
  • 原文地址:https://www.cnblogs.com/wsl-lld/p/13393551.html
Copyright © 2011-2022 走看看