01-05-2025, 09:57 PM
Both are right. It's a lot like saying, "What's the square root of 4?" Well heck, that's 4 AND -4! Both are correct.
So it you always want a positive value, do this:
result = (num MOD mod_value + mod_value) MOD mod_value
Or, specifically in your case:
result = (-6 MOD 7 + 7) MOD 7
Quote:Floored division:
In this method, Quotient is determined by the floor division of Dividend and Divisor. It rounds off the quotient to the nearest smallest integer. So remainder can be computed from the following expression:
r = a – b* floor(a/b), where r, a, b are Remainder, Dividend and Divisor respectively.
Example:
=> -7 % 5 = -7 – 5 *( floor(-7/5) )
= -7 – 5*( floor(-1.4) )
= -7 – 5*( -2)
= -7+10
= 3
In Python, floor division is used to determine the remainder.
Truncated division:
In this method, Quotient is determined by the truncate division of Dividend and Divisor. It rounds off the quotient towards zero. So remainder can be computed from the following expression:
r = a – b* trunc(a/b), where r, a, b are Remainder, Dividend and Divisor respectively.
Example:
=> -7 % 5 = -7 – 5 *( trunc(-7/5) )
= -7 – 5*( trunc(-1.4) )
= -7 – 5*( -1)
= -7+5
= -2
In C/C++, truncate division is used to determine the remainder
Thus, In programming languages which uses truncate division to find the remainder, we always find remainder as (a%b + b)%b (add quotient to remainder and again take remainder) to avoid negative remainder and get the correct result.
So it you always want a positive value, do this:
result = (num MOD mod_value + mod_value) MOD mod_value
Or, specifically in your case:
result = (-6 MOD 7 + 7) MOD 7
Code: (Select All)
Print -6 Mod 7
Print (-6 Mod 7 + 7) Mod 7