Here you can find the source of modInverse(int n, int mod)
public static int modInverse(int n, int mod)
//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; } } }