# Modulo and integer division in C++ and C languages.

From the point of view of C++, C: -17 % 5 = -2 -17 / 5 = -3 But from the point of view of mathematics (and python😁): -17 % 5 = 3 -17 / 5 = -4 Explain inner logic of compiler (e. g. gcc) to me. How it calculates? Why designers chose such logic in compiler, instead of mathematical approach?

1/8/2018 10:51:03 AM

\__(° = °)__/21 Answers

New AnswerMaybe this approach suits for old languages(they didn't notice difference and didn't want to aim to design the language more consistently and of course can't solve and notice all features related with mathematics)? But the in modern (don't argue🙃) languages they decided to make it more correctly from the point of view of mathematics🤔 Honestly, I dislike these implicit things in languages zoo, but nevertheless we have what we have. For example, in JS we have strange thing as **null**. And they can't fix it because of backward compatibility in legacy codes😁 A surprising, but very interesting world of programming languages💃

See: https://stackoverflow.com/questions/24074869/why-is-the-behavior-of-the-modulo-operator-different-between-c-and-ruby-for

-- found this which maybe of interest. Originally, MOD(n, m) was defined only for positive values of both m and n, and leaves the result to be implementation-dependent when either of m or n is negative.

In Mathematics we have : Dividend = Divisor * Quotient + Remainder so according to your words :) : In C++ we have: (-17) = (+5) * (-3) + (-2) => (-17) = (-15) + (-2) =>(-17) = (-17) => So its correct :) In Python we have : (-17) = (+5) * (-4) + (+3) => (-17) = (-20) + (+3) =>(-17) = (-17) => So its correct :) So don't say Mathematics and Python says other answer :) because both of them (C++ & Python) are correct just having different processes :)

Non euclidean division is used in c and it's variants. You can use euclidean division, but you have to do so manually. https://code.sololearn.com/ct8gPZL2Qj8R/?ref=app

At first glance, I'd attempt to implement what is referred to as 'typecasting'. Perhaps try something *similar* to the following (toy around with it some) ... *C++ : int var1 = (int)(-17 % 5); int var2 = (int)(-17 / 5); *Python : var1, var2 = int(-17 % 5), int(-17 / 5)

mod operation for any negative operand is platform/language (and person 😀) dependent https://en.m.wikipedia.org/wiki/Modulo_operation

https://www.cprogramming.com/tutorial/modulus.html it is converted into integer numbers then calculate using boxing unboxing concepts......

I think what 4rontender is pointing out clearly is that -n%m in .cpp != -n%m in .py & -n/m in .cpp != -n/m in .py

c & c++ are hardware related languages. it is searched for the fastest and most direct method to compute modulo. IEEE allows you to: IEEE 754 defines a remainder function where the quotient is a/n rounded according to the round to nearest convention. Thus, the sign of the remainder is chosen to be nearest to zero.