Negative mods aren't handled well

example: -1 mod 4 should return 3

Answers

  • edited November 2013

    -1 mod 4 should return -1

    because the standard order of precedence means that the unary minus is performed before the modulus.

    I have edited the above statement because the original was a mistake and didn't match the first line. Sorry about that, I should read my posts more carefully.

  • edited November 2013

    Hmmm... That's not what I see! b-(

    println((-1) % 4);
    

    AFAIK, all unary operators have higher precedence than any other binary operators.
    Both for programming & mathematics!!! ~:>

    Modulo binary operator % should never happen before negative unary operator -!!! 8-X

  • i always (n + m) % m (which only works if n is never going below -m, which it isn't, usually)

    (((n % m) + m) % m) should work. longwinded though.

  • edited November 2013

    Excellent @koogs! o=>

    final int n = -1, m = 4;
    
    println(n % m);             // -1
    println((n + m) % m);       // 3
    println((n % m  + m) % m);  // 3
    
    exit();
    
  • @koogs of course - looking for wrap around values - well spotted

Sign In or Register to comment.