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
  • 19,483
  • 10
  • 67
  • 96
mlnyc
  • 2,566
  • 2
  • 22
  • 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
  • 66,530
  • 15
  • 117
  • 170
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
  • 11,964
  • 4
  • 34
  • 43
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
  • 16,409
  • 7
  • 51
  • 73