Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

real modulo operator in C/C++? [duplicate]

Tags:

c++

c

modulo

Possible Duplicate:
How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

From what I understand (see Modulo operator with negative values and Modulo operation) C & C++ have a "remainder" operator a % b but no operator that actually does modular arithmetic when the LHS is negative.

Several languages do have such a function. Is it possible to build an efficient function in C/C++ (or is there no efficient way to do it on i686/x64 CPUs)?

Currently I use (n * b + a) % b where n is picked such that I'm fairly sure the entire LHS is non-negative, but inevitably code gets changed and bugs sometimes occur.

Note: in case it's not clear, by modular arithmetic I mean an operator such that a + b % b = a % b for all integers a and all positive integers b.

like image 422
dhardy Avatar asked Dec 05 '22 14:12

dhardy


2 Answers

There is no simple way to do it, however it is more efficient if you create a two-line solution, and spare a multiplication plus determining n.

inline int modulo(int a, int b) {
  const int result = a % b;
  return result >= 0 ? result : result + b;
}

Also, if you need to work correctly for negative b numbers as well, add to the beginning:

          if(b < 0) return modulo(-a, -b);
like image 50
Lorlin Avatar answered Dec 09 '22 15:12

Lorlin


I would suggest a function like the one above, but using inline int modulo(int a, int b) {} (just as if the operator existed in C++). Personnally I don't use negative numbers often, and still think you should keep % whenever your code doesn't use negative numbers.

like image 30
maxbc Avatar answered Dec 09 '22 14:12

maxbc