Java Integer Mod modularInvert(int num, int modulus)

Here you can find the source of modularInvert(int num, int modulus)

Description

Returns modular inverse of given number with given modulus

License

Open Source License

Parameter

Parameter Description
num Number to invert
modulus Modulus under which to invert

Return

Modular inverse

Declaration

public static int modularInvert(int num, int modulus) 

Method Source Code

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

public class Main {
    /**/*  ww w  .j a  v  a  2s  . co m*/
     * Returns modular inverse of given number with given modulus
     * 
     * @param num
     *          Number to invert
     * @param modulus
     *          Modulus under which to invert
     * @return Modular inverse
     */
    public static int modularInvert(int num, int modulus) {
        int tmp; // convert to positive member of equivalence class if necessary
        return ((tmp = (extendedEuclidian(modulus, num)[1] % modulus)) > 0) ? tmp : tmp + modulus;
    }

    /**
     * Runs extended Euclidian algorithm. We can input <number, modulus> to calculate
     * number^-1 % modulus iff we already know gcd(number, modulus) = 1. In this case,
     * number^-1 is return[1].
     * 
     * @param num1
     *          First number
     * @param num2
     *          Second number
     * @return Array of three ints. {GCD, X, Y} where X,Y are from num1*X + num2*Y =
     *         gcd(num1,num2)
     */
    public static int[] extendedEuclidian(int num1, int num2) {
        int a = 1, b = 0;
        int prevA = 0, prevB = 1;

        int quotient, remainder, m, n;

        while (num1 != 0) {
            // compute q and r
            quotient = num2 / num1;
            remainder = num2 % num1;

            // mod--sorta
            m = prevA - quotient * a;
            n = prevB - quotient * b;

            // prepare for next iteration
            prevA = a;
            prevB = b;
            a = m;
            b = n;
            num2 = num1;
            num1 = remainder;
        }

        return new int[] { num2, prevB, prevA };
    }
}

Related

  1. modMultiply(long a, long b, int m)
  2. modPos(int divisor, int dividend)
  3. modSubtract(long a, long b, int m)
  4. modularExp(long base, long exp, int modulus)
  5. modularInverses(int p)
  6. modulateCircularIndex(int index, int seqLength)
  7. modulo(int a, int b)
  8. modulo(int a, int b)
  9. modulo(int dividend, int divisor)