0

Ok So I know and understand the difference between MOD and REM. I also am aware that C's % operation is a REM operation. I wanted to know, and could not find online, if there is some C library or function for an explicit MOD.

Specifically, I'd like (-1)%4 == 3 to be true. In C (-1)%4 = -1 since it is a remainder. And preferably I'd like to avoid using absolute values and even better would be to utilize some built in function that I can't seem to find.

Any advice will be much appreciated!

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
mlnyc
  • 2,636
  • 2
  • 24
  • 29
  • See [How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers](http://stackoverflow.com/questions/4003232/how-to-code-a-modulo-operator-in-c-c-obj-c-that-handles-negative-numbers) – godel9 Nov 08 '13 at 14:48

3 Answers3

3

The best option I can think of is to compute:

((-1 % 4) + 4 ) % 4

Here you may replace -1 with any value and you will get MOD not REM.

Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
0

Just do,

int mod(int a, int b)
{
    int res = a % b;
    return(res < 0 ? (res + b) : res);
}

Every negative res content after MOD operation is added to b to get modulus of a & b.

Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46
0

The most common way to do what you expect is:

((a % b) + b ) % b

It works because (a % b) is a number in ]-b; b[ so (a % b) + b is positive (in ]0; 2 * b[) and adding b did not changed the mod.

Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75