Here you can find the source of modularInvert(int num, int modulus)
Parameter | Description |
---|---|
num | Number to invert |
modulus | Modulus under which to invert |
public static int modularInvert(int num, int modulus)
//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 }; } }