2

I have a question about performing of division with remainder of integers in C/C++. It is said that in operation of division between two integers, if the result can not be expressed as an integer, its part that is not integer are removed in decimal. For example, int a=17; a/=3; /pseudo float a, gets the value of 5.6666../ so the result is 5. This is result of a normal division with remainder in arithmetic at the same time due to the part after point(6666..) which is actually division of the remainder(2) by 3. This works on my compter but is it definitely reliable or I have to declare with float and then cast to int with floor for safe? Which is better for perfonmance and safe? Thanks in advance.

user2561614
  • 51
  • 1
  • 6

3 Answers3

4

Arithmetic operation on integers in C++ does not depend of the computer.
If a and b are integers, a / b will always give you the integer quotient of the division and a % b will always give you the remainder of the integer division.

In terms of performance, you can take a look at this StackOverflow question, but it seems to be architecture dependant.

Community
  • 1
  • 1
Levans
  • 11,766
  • 3
  • 38
  • 47
1

You should use a / b and a % b for integer division and remainder. As Levans says, these are guaranteed to give you the "correct" values independent of your hardware (at least if a and b are positive). With floating point arithmetic, the result can be affected by rounding errors, which can also be hardware-dependent.

oseiskar
  • 2,882
  • 2
  • 17
  • 22
0

So, instead of integer modulo, you can get two floats then multiply one float with inverse of the divider :

17.0 * 0.33 = 5.61

then floor() it into an integer and subtract :

5.61 - 5 ----> 0.61

then multiply the result with inverse of 0.33:

0.61 * 3 ------> 1.83 

then ceil() it

2    ----> this is 17%3

This is 14 times slower than using direct modulus, according to user "Oseiskar " 's benchmarking.

huseyin tugrul buyukisik
  • 9,464
  • 3
  • 39
  • 81