Java Integer Mod modInverse(int n, int mod)

Here you can find the source of modInverse(int n, int mod)

Description

mod Inverse

License

Open Source License

Declaration


public static int modInverse(int n, int mod) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {

    /* source : http://www.liafa.univ-paris-diderot.fr/~carton/Enseignement/CalculFormel/Style/ModArith/Gcd.java*/
    public static int modInverse(int n, int mod) {
        int[] g = extgcd(mod, n);
        if (g[0] != 1) {
            return -1; // n et mod ne sont pas premiers entre eux
        } else {//w w w  . java2s.  c  o  m
            return reduce(g[2], mod);
        }
    }

    /* source : http://www.liafa.univ-paris-diderot.fr/~carton/Enseignement/CalculFormel/Style/ModArith/Gcd.java*/
    public static int[] extgcd(int m, int n) {
        // Both arrays ma and na are arrays of 3 integers such that
        // ma[0] = m ma[1] + n ma[2] and na[0] = m na[1] + n na[2]
        int[] ma = new int[] { m, 1, 0 };
        int[] na = new int[] { n, 0, 1 };
        int[] ta; // Temporary variable 
        int i; // Loop index
        int q; // Quotient
        int r; // Rest

        // Exchange ma and na if m < n
        if (m < n) {
            ta = na;
            na = ma;
            ma = ta;
        }

        // It can be assumed that m >= n
        while (na[0] > 0) {
            q = ma[0] / na[0]; // Quotient
            for (i = 0; i < 3; i++) {
                r = ma[i] - q * na[i];
                ma[i] = na[i];
                na[i] = r;
            }
        }
        return ma;
    }

    /* source : http://www.liafa.univ-paris-diderot.fr/~carton/Enseignement/CalculFormel/Style/ModArith/Gcd.java*/
    public static int reduce(int n, int mod) {
        int m = n % mod; // -mod < m < mod

        if (m >= 0) {
            return m;
        } else {
            return m + mod;
        }
    }
}

Related

  1. modifyBase32AtIndex(final String s, final int index)
  2. modifyDummyString(String dummyString, int beginTag, int endTag)
  3. modifyPublicPortCheckRange(String modifiedVal, int dashCnt)
  4. modifyString(char firstCharacter, String srcString, int indexOfSubstring)
  5. modInverse(int a, int n)
  6. modMultiply(long a, long b, int m)
  7. modPos(int divisor, int dividend)
  8. modSubtract(long a, long b, int m)
  9. modularExp(long base, long exp, int modulus)