Java Utililty Methods Integer Mod

List of utility methods to do Integer Mod

Description

The list of methods to do Integer Mod are organized into topic(s).

Method

intmodInverse(int a, int n)
calculates and returns the inverse of a modulo n, both of which should be positive.
int i = n, v = 0, d = 1;
while (a > 0) {
    int t = i / a, x = a;
    a = i % x;
    i = x;
    x = d;
    d = v - t * x;
    v = x;
...
intmodInverse(int n, int mod)
mod Inverse
int[] g = extgcd(mod, n);
if (g[0] != 1) {
    return -1; 
} else {
    return reduce(g[2], mod);
intmodMultiply(long a, long b, int m)
Modular multiplication.
Returns ( a * b )( mod m ).
Differs from ( a * b ) % m in that it always returns non-negative value and never overflows.
If m = 0, #NOT_FOUND is returned.
if (m <= 0) {
    if (m == 0)
        return NOT_FOUND;
    m = -m;
a %= m;
b %= m;
a = (a * b) % m;
...
intmodPos(int divisor, int dividend)
Calculates (value mod size).
return divisor >= 0 ? divisor % dividend : ((divisor + 1) % dividend) - 1 + dividend;
intmodSubtract(long a, long b, int m)
Modular subtraction.
Returns ( a - b )( mod m ).
Differs from ( a - b ) % m in that it always returns non-negative value and never overflows.
If m = 0, #NOT_FOUND is returned.
if (m <= 0) {
    if (m == 0)
        return NOT_FOUND;
    m = -m;
a %= m;
b %= m;
a = (a - b) % m;
...
intmodularExp(long base, long exp, int modulus)
Compute modular exponentiation in O(log exp).
base = base % modulus; 
int toRet = 1;
long[] modExpResults = new long[(int) log2(exp + 1) + 1]; 
modExpResults[0] = (base % modulus); 
for (int i = 1; i < modExpResults.length; i++) {
    modExpResults[i] = (modExpResults[i - 1] * modExpResults[i - 1]) % modulus;
int counter = 0;
...
int[]modularInverses(int p)
This function returns the multiplicative inverses of the integers [0, 1, ..., p-1] in mod p arithmetic.
int[] inverses = new int[p];
for (int i = 1; i < p; i++) {
    int inverse = 0;
    for (int j = 1; j < p; j++) {
        if (((j * i) % p) == 1) {
            inverse = j;
            break;
    if (inverse == 0) {
        throw new IllegalArgumentException(p + " is not a prime.");
    inverses[i] = inverse;
return inverses;
intmodularInvert(int num, int modulus)
Returns modular inverse of given number with given modulus
int tmp; 
return ((tmp = (extendedEuclidian(modulus, num)[1] % modulus)) > 0) ? tmp : tmp + modulus;
intmodulateCircularIndex(int index, int seqLength)
Takes a point on a circular location and moves it left until it falls at the earliest possible point that represents the same base.
if (seqLength == 0) {
    return index;
while (index > seqLength) {
    index -= seqLength;
return index;
intmodulo(int a, int b)
Performs a modulus operation in Python style.
if (b == 0)
    throw new IllegalArgumentException("Division by Zero!");
if (a > 0 && b > 0 && b > a)
    return a;
boolean isMinus = Math.abs(b - (a - b)) < Math.abs(b - (a + b));
if (isMinus) {
    while (a >= b) {
        a -= b;
...