Java Integer Mod Mod(int a, int b)

Here you can find the source of Mod(int a, int b)

Description

The result of the "modulus" operator (a mod b) is defined as the remainder of the integer division (a / b).

License

Open Source License

Declaration

public static int Mod(int a, int b) 

Method Source Code

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

public class Main {
    /**//from   ww w.ja v a2  s. c om
     * The result of the "modulus" operator (a mod b) is defined as the
     * remainder of the integer division (a / b). If BOTH a, b are positive,
     * then Java's % (remainder) operator gives the correct results. If at least
     * one of the operands could be negative, the following method can be used
     * to implement the mathematical definition of the mod operator:
     * Examples:
     *     13 mod  4 =  1
     *    -13 mod  4 =  3
     *     13 mod -4 = -3
     *    -13 mod -4 = -1
     *      0 mod  4 =  0
     *      4 mod  0 =  4
     */
    public static int Mod(int a, int b) {
        if (b == 0)
            return a;
        if (a * b >= 0)
            return a - b * (a / b);
        else
            return a - b * (a / b - 1);
    }
}

Related

  1. mod(final int dividend, final int divisor)
  2. mod(final int dividend, final int divisor)
  3. mod(final int n, final int N)
  4. mod(int a, int b)
  5. mod(int a, int b)
  6. mod(int a, int b)
  7. mod(int a, int n)
  8. mod(int a, int n)