Java BigInteger Calculate mods(BigInteger v, BigInteger m)

Here you can find the source of mods(BigInteger v, BigInteger m)

Description

Signed mod.
The value returned lies in range [ -( |m| - 1 ) / 2 ..

License

Open Source License

Parameter

Parameter Description
v a value
m a modulus

Exception

Parameter Description
ArithmeticException when m = 0

Return

v (mod m)

Declaration

public static BigInteger mods(BigInteger v, BigInteger m)
        throws ArithmeticException 

Method Source Code

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

import java.math.BigInteger;

public class Main {
    /**//from   ww  w .jav  a2  s . co  m
     * Signed mod.<br>
     * The value returned lies in range [ -( |m| - 1 ) / 2 .. |m| / 2 ].<br>
     * If m = 0 then ArithmeticException is thrown.
     * @param v a value
     * @param m a modulus
     * @return v (mod m)
     * @throws ArithmeticException when m = 0
     */
    public static BigInteger mods(BigInteger v, BigInteger m)
            throws ArithmeticException {
        int signum = m.signum();
        if (signum == 0)
            throw new ArithmeticException("Zero modulus");
        if (signum < 0)
            m = m.negate();
        v = v.remainder(m);
        if (v.compareTo(m.shiftRight(1)) > 0)
            v = v.subtract(m);
        else if (v.compareTo(m.subtract(BigInteger.ONE).shiftRight(1)
                .negate()) < 0)
            v = v.add(m);
        return v;
    }
}

Related

  1. maskBits(BigInteger value, int bits)
  2. min(BigInteger a, BigInteger b)
  3. modPow(BigInteger base, BigInteger e, BigInteger m)
  4. modPowByte(byte[] arg, BigInteger e, BigInteger n)
  5. modPowLong(BigInteger n, long exponent, BigInteger modulo)
  6. modulus(BigInteger value, BigInteger divider, int modulo, int... weight)
  7. multi_exponent(BigInteger[] base, BigInteger[] exponent, BigInteger modulus)
  8. multiply(BigInteger x, BigInteger y)
  9. negative(BigInteger n)