Java Integer Mod mod(final int dividend, final int divisor)

Here you can find the source of mod(final int dividend, final int divisor)

Description

Java's modulus operator is disappointingly different to other languages.

License

Open Source License

Declaration


public static int mod(final int dividend, final int divisor) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*from   w  w  w.j a v a 2s  . c o  m*/
     * Java's modulus operator is disappointingly different to other languages. I wanted to take a
     * number and corral it into the range 0 ... divisor which you can do with a % in Python. However,
     * in Java you get the 'wrong' answer for negative dividends. So the hack is to add (n * divisor)
     * to the dividend to make it positive.
     */

    public static int mod(final int dividend, final int divisor) {

        assert divisor > 0 : "have not implemented negative divisors yet";

        int dividend2 = dividend;

        if (dividend2 < 0) {
            int makePositive = (1 + -1 * dividend2 / divisor) * divisor;

            dividend2 = dividend2 + makePositive;
        }

        return dividend2 % divisor;

    }
}

Related

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