0

Let's say I have (-5) mod 8.

I tried it in both languages Java and C, and they gave me a -5 result when I was expecting 3.

Why is this happening? Can a modulus be negative? And what should I change to get the correct result?

Java code

public class Example {
    public static void main(String[] args) {
        int x;
        x = -5%8;
        System.out.println(x);
    }
}

C code

int main(){
    int x;
    x = -5%8;
    printf("%d", x);
}

OUTPUTS

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John
  • 81
  • 2
  • 12
  • 1
    In Java you can use `Math.floorMod(dividend, divisor)`. I have no clue about C (and you should probably open two separate questions when asking about two completely different programming languages). – Bobulous May 13 '17 at 12:50
  • `(8 * -1) + 3 = -5`; `(8 * 0) - 5 = -5` there's no rule about which to choose in c89. – pmg May 13 '17 at 12:51
  • @pmg The latest C standard states that `((a/b)*b + a%b) == a` must be true, if `a/b` can be represented. That rules out `3` as the remainder when `a == -5` and `b == 8` because `-5/8` is `0`. – Andrew Henle May 13 '17 at 12:55
  • 1
    Possible duplicate of [Why does C++ output negative numbers when using modulo?](http://stackoverflow.com/questions/11630321/why-does-c-output-negative-numbers-when-using-modulo) – phuclv May 13 '17 at 13:07
  • 1
    [Does either ANSI C or ISO C specify what -5 % 10 should be?](http://stackoverflow.com/q/3609572/995714), [Modulo operation with negative numbers](http://stackoverflow.com/q/11720656/995714), [Why is the behavior of the modulo operator (%) different between C and Ruby for negative integers?](http://stackoverflow.com/q/24074869/995714) – phuclv May 13 '17 at 13:09
  • 1
    **C89** has this text: "If either operand is negative, whether the result of the `/` operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is **implementation-defined**, as is the sign of the result of the `%` operator." C99 and later have made quotient and modulus perfectly defined with "truncation towards zero". – pmg May 13 '17 at 13:12
  • Short answer: `%` is not `mod`. –  May 13 '17 at 16:33

4 Answers4

6

The % operator is treated as a remainder operator, so the sign of the result is the same as that of the dividend.

If you want a modulo function, you can do something like this:

int mod(int a, int b)
{
    int ret = a % b;
    if (ret < 0)
        ret += b;
    return ret;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dishonered
  • 8,449
  • 9
  • 37
  • 50
2

Why is this happening?

It's defined that way in C. % is the remainder operator. Per 6.5.5 Multiplicative Operators, paragraph 6 of the C Standard:

When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a ; otherwise, the behavior of both a/b and a%b is undefined.

It's also defined that way in Java. Per 15.17.3. Remainder Operator % of the Java 8 specification:

The binary % operator is said to yield the remainder of its operands from an implied division; the left-hand operand is the dividend and the right-hand operand is the divisor.

In C and C++, the remainder operator accepts only integral operands, but in the Java programming language, it also accepts floating-point operands.

The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.

This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is -1 (the remainder is 0).

It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. Moreover, the magnitude of the result is always less than the magnitude of the divisor.

So the remainder - the result of the % operator - must have the same sign as the dividend - the first value, before the % operator.

Andrew Henle
  • 32,625
  • 3
  • 24
  • 56
0

You should have look at Stack Overflow question What's the difference between “mod” and “remainder”?.

To get mod positive do -


C Code -

int main(){
    int a, b;
    scanf("%d %d", &a, &b);
    int rem  = a%b;
    if (rem<0)
        rem += b;
    printf("%d", rem);
    return 0;
}

Similar would be the Java code.

Basically the approach is that first take mod irrespective of the sign (to make the magnitude of the answer less than that of divisor), and if the answer is negative then add the divisor to it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
GAURANG VYAS
  • 689
  • 5
  • 16
-1

It's not about the number is being negative or positive. 5%8 would return 5 because that's how mod operator works.

If you want 3 or -3 as result, you need to do 8%5 or -8%5 respectively.

Here's the documentation, this is what it says:

divides one operand by another and returns the remainder as its result.

So, it's always fir operand divided by second. Also, if you want positive result then you can do:

Math.abs(-8%5);
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
  • Also if you only want positive results you can take the absolute value using `Math.abs()` –  May 13 '17 at 12:45
  • 2
    He means `(-5) % 8` not `-(5 % 8)`. – pmg May 13 '17 at 12:45
  • @pmg I have updated the answer with example and documentation. – Darshan Mehta May 13 '17 at 12:47
  • but (-8) mod 5 equals to 2 and Math.abs(-8%5); gives 3 – John May 13 '17 at 12:53
  • @John (-8) mod 5 equals to 3 and not 2. Perhaps you are trying to do something else and not `mod`? – Darshan Mehta May 13 '17 at 13:17
  • @DarshanMehta -8 = 2 * -5 +2 – John May 13 '17 at 13:37
  • @John `-8 = (1 * -5) -3` as well, and that's how `mod` operator works. – Darshan Mehta May 13 '17 at 13:41
  • @DarshanMehta what is -3? modulo can't be negative. – John May 13 '17 at 13:49
  • @John did you read tons of other duplicates? those answers have already explained clearly that C doesn't have a modulo operator. It only has **remainder** operator – phuclv May 14 '17 at 15:36
  • @LưuVĩnhPhúc sure but in my question i provided two different codes for two different languages well explained with the output results and i also ask for a modulo code that works to help me with my project. I don't understand the downvotes and your duplicates. Nobody in your duplicates provides an answer about a modulo code that works. – John May 15 '17 at 13:49
  • then you didn't read all the answers carefully. there are a lot of working solutions – phuclv May 15 '17 at 13:53
  • @LưuVĩnhPhúc maybe, thanks for your time sir, have a nice day – John May 15 '17 at 17:30