News for hackers. Stuff that matters.
Re:Integers in C quiz by veltas on Sunday September 04, 2022 @09:14AM (#32712694)
The really useful fact of C's remainder operator is that: x == x / y * y + x % y, provided nothing overflowed. This is usually what you want when doing accurate calculations with integer division.
Re:Integers in C quiz by xigoi on Sunday September 04, 2022 @02:06PM (#32715845)
The modulo operation together with floor division also has this property. And unlike C's operators, it also has the useful property that (x + y) % y == x % y.
Re:Integers in C quiz by kccqzy on Monday September 05, 2022 @06:26PM (#32730235)
That's an inherent property of both the modulus interpretation and the remainder interpretation.

Haskell does it right. Instead of having operators like %, it gives the programmer choice to choose either the modulus or the remainder. Using GP's example:

    ghci> 2 `div` (-5)
    -1
    ghci> 2 `mod` (-5)
    -3

    ghci> 2 `quot` (-5)
    0
    ghci> 2 `rem` (-5)
    2
And we have both (x `quot` y)*y + (x `rem` y) == x and (x `div` y)*y + (x `mod` y) == x