Help in remainder

guys if we do -27%5 we get -2 as remainder (c/c++) but as the range for a remainder will 0<=r<(5-1) so why (c++/c) give wrong ans.
also remainder can be negative ?

Remainder is always from 0 to N-1, where N is the number you are doing modulo with. So, when the integer you are doing mod with is negative, to bring it in the range, add N to it.
i.e. in the above example, 5+(-27℅5)=3

1 Like

bro but why c++ show -2 instead of showing correct result (-3)

also if we asked a question what is remainder of -27%5 ans 3 will be correct irrespective of any language

Yes, in maths it’s correct, but there’s a type specific to every language. For C/C++, precedence order follows. The emphasis is always on left operand’s sign i.e. if left operand is negative, the answer will be negative.
A general rule can be said like this
L R Res
+ + +
+ - +
- + -
- - -

Whereas in python, even if the result is negative, it automatically changes its range.

but for
l r res


we need to add n to get correct result (c/c++)

Yes correct

bro i will tell one thing today my sir asked what is -5%4 (c/c++) i said 3 he said it will be -1 and i told him it will be in 0 to n-1. he compiled it show me the result and it -1 now two days
ago i was solving a problem in codechef about modulo for negative number until i did not add 1e+7 it was not accepted codechef but mathematically it was correct so got confused

Yes bro, -5℅4 returns -1. As I said above in C/C++, the sign of the returning integer depends on the sign on the left hand operand. In layman language, in C++, it does this, -5℅4= - (5%4) = -1.

But in languages like python, the returning integer depends on sign of divisor. In python, it goes like this
-5℅4 =(-2*4+3)℅4 =3.
Mathematically you are perfectly correct, but what you are asking is language specific. So you need to add modulo in cpp.