Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: which operator for modulo (% doesn't work with negative numbers)

If I try

int a=(-2)%6

I get -2 instead of 4.

Why does it behave this way with negative numbers?

like image 783
c0dehunter Avatar asked Feb 08 '12 22:02

c0dehunter


People also ask

Does modulo work with negative numbers?

If both the divisor and dividend are negative, then both truncated division and floored division return the negative remainder.

What the modulus operator (%) does?

The modulo operator, denoted by %, is an arithmetic operator. The modulo division operator produces the remainder of an integer division. produces the remainder when x is divided by y.

Can modulo return a negative?

These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results.

Does modulo work on negative numbers in C?

Modulus operator with negative numbers If we have negative numbers, the result will be based on the left operand's sign, if the left operand is positive – the result will be positive, and if the left operand is negative – the result will be negative.


2 Answers

% does a remainder operation in Java.

To get a proper modulus, you can use the remainder in a function:

It's shortest using ternary operator to do the sign fixup:

private int mod(int x, int y)
{
    int result = x % y;
    return result < 0? result + y : result;
}

For those who don't like the ternary operator, this is equivalent:

private int mod(int x, int y)
{
    int result = x % y;
    if (result < 0)
        result += y;
    return result;
}
like image 195
Don Roby Avatar answered Oct 14 '22 04:10

Don Roby


Because if you divides -2 by 6, you will get -2 as remainder. % operator will give the remainder just like below;

int remainder = 7 % 3;  // will give 1
int remainder2 = 6 % 2; // will give 0

To get the modulo:

    // gives m ( mod n )
public int modulo( int m, int n ){
    int mod =  m % n ;
    return ( mod < 0 ) ? mod + n : mod;
}
like image 22
emin Avatar answered Oct 14 '22 06:10

emin