My friend said that there are differences between "mod" and "remainder".
If so, what are those differences in C and C++? Does '%' mean either "mod" or "rem" in C?
There is a difference between modulus (Euclidean division) and remainder (C's % operator). For example:
-21 mod 4 is 3 because -21 + 4 x 6 is 3.
But -21 divided by 4 with truncation towards 0 (as C's / operator)
gives -5 with a remainder (C -21 % 4) of -1.
For positive values, there is no difference between Euclidean and truncating division.
See https://en.wikipedia.org/wiki/Euclidean_division#Other_intervals_for_the_remainder - C's choice of truncating the remainder towards 0 (required since C99) forces a negative remainder range for negative quotients. Even in C89, when Euclidean division was allowed by the standard for /
If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
(-21/4) * 4 + (-21%4) == -21; C99 and later require (-5) * 4 + (-1), not Euclidean -6 and 3.
Does '%' mean either "mod" or "rem" in C?
In C, % is the remainder1.
..., the result of the / operator is the algebraic quotient with any fractional part discarded ... (This is often called "truncation toward zero".) C11dr §6.5.5 6
The operands of the % operator shall have integer type. C11dr §6.5.5 2
The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder ... C11dr §6.5.5 5
What's the difference between “mod” and “remainder”?
C does not define a "mod" nor "modulo" operator/function, such as the integer modulus function used in Euclidean division or other modulo.
C defines remainder.
Let us compare "remainder" per the % operator to the Euclidean "mod".
"Euclidean mod" differs from C's a%b operation when a is negative.
// a % b, the remainder after an integer division that truncates toward 0.
7 % 3 --> 1
7 % -3 --> 1
-7 % 3 --> -1
-7 % -3 --> -1
"Mod" or modulo as in Euclidean division. The result is always 0 or positive.
7 modulo 3 --> 1
7 modulo -3 --> 1
-7 modulo 3 --> 2
-7 modulo -3 --> 2
Candidate modulo code:
int modulo_Euclidean(int a, int b) {
int m = a % b;
if (m < 0) {
// m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
m = (b < 0) ? m - b : m + b;
}
return m;
}
Note about floating point: double fmod(double x, double y), even though called "fmod", it is not the same as Euclidean division "mod", but similar to C integer remainder:
The fmod functions compute the floating-point remainder of x/y. C11dr §7.12.10.1 2
fmod( 7, 3) --> 1.0
fmod( 7, -3) --> 1.0
fmod(-7, 3) --> -1.0
fmod(-7, -3) --> -1.0
Disambiguation: C also has a similar named function double modf(double value, double *iptr) which breaks the argument value into integral and fractional parts, each of which has the same type and sign as the argument. This has little to do with the "mod" discussion here except name similarity.
[Edit Dec 2020]
For those who want proper functionality in all cases, an improved modulo_Euclidean() that 1) detects mod(x,0) and 2) a good and no UB result with modulo_Euclidean2(INT_MIN, -1). Inspired by 4 different implementations of modulo with fully defined behavior.
int modulo_Euclidean2(int a, int b) {
if (b == 0) TBD_Code(); // perhaps return -1 to indicate failure?
if (b == -1) return 0; // This test needed to prevent UB of `INT_MIN % -1`.
int m = a % b;
if (m < 0) {
// m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
m = (b < 0) ? m - b : m + b;
}
return m;
}
1 Prior to C99, C's definition of % was still the remainder from division, yet then / allowed negative quotients to round down rather than "truncation toward zero". See Why do you get different values for integer division in C89?. Thus with some pre-C99 compilation, % code can act just like the Euclidean division "mod". The above modulo_Euclidean() will work with this alternate old-school remainder too.
sign of remainder will be same as the divisible and the sign of modulus will be same as divisor.
Remainder is simply the remaining part after the arithmetic division between two integer number whereas Modulus is the sum of remainder and divisor when they are oppositely signed and remaining part after the arithmetic division when remainder and divisor both are of same sign.
Example of Remainder:
10 % 3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]
-10 % 3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]
10 % -3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]
-10 % -3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]
Example of Modulus:
5 % 3 = 2 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is also positively signed. As both remainder and divisor are of same sign the result will be same as remainder]
-5 % 3 = 1 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is positively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor -2 + 3 = 1]
5 % -3 = -1 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is negatively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor 2 + -3 = -1]
-5 % -3 = -2 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is also negatively signed. As both remainder and divisor are of same sign the result will be same as remainder]
I hope this will clearly distinguish between remainder and modulus.
In C and C++ and many languages, % is the remainder NOT the modulus operator.
For example in the operation -21 / 4 the integer part is -5 and the decimal part is -.25. The remainder is the fractional part times the divisor, so our remainder is -1. JavaScript uses the remainder operator and confirms this
console.log(-21 % 4 == -1);
The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.
Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.
Modulus, in modular arithmetic as you're referring, is the value left over or remaining value after arithmetic division. This is commonly known as remainder. % is formally the remainder operator in C / C++. Example:
7 % 3 = 1 // dividend % divisor = remainder
What's left for discussion is how to treat negative inputs to this % operation. Modern C and C++ produce a signed remainder value for this operation where the sign of the result always matches the dividend input without regard to the sign of the divisor input.
% is a remainder(leftover after dividend / divisor) NOT modulus.
You could write your own modulus function using the remainder(%) by the relation
((n%m)+m)%m
where `n` is the given number and `m` is the modulus
Find below the difference between the remainder and modulus values for the range n = (-7,7) and m = 3
n -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
-------------------------------------------------------------------------
%(-m) -1 0 -2 -1 0 -2 -1 0 1 2 0 1 2 0 1 => remainder
% m -1 0 -2 -1 0 -2 -1 0 1 2 0 1 2 0 1 => remainder
mod m 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 => ((n%m)+m)%m
mod(-m) -1 0 -2 -1 0 -2 -1 0 -2 -1 0 -2 -1 0 -2 => ((n%m)+m)%m
Tips to remember:
n%(-m) = +(remainder)
(-n)%(m) = -(remainder)
sign of 'm' doesn't matter
n mod (-m) = -(result)
(-n) mod m = +(result)
sign of 'n' doesn't matter
For +ve 'n' and '%(-m)' or '%m' or 'mod m' gives the same remainder
In mathematics the result of the modulo operation is the remainder of the Euclidean division. However, other conventions are possible. Computers and calculators have various ways of storing and representing numbers; thus their definition of the modulo operation depends on the programming language and/or the underlying hardware.
7 modulo 3 --> 1
7 modulo -3 --> -2
-7 modulo 3 --> 2
-7 modulo -3 --> -1
Related
In a C program I was trying the below operations (Just to check the behavior)
x = 5 % (-3);
y = (-5) % (3);
z = (-5) % (-3);
printf("%d ,%d ,%d", x, y, z);
It gave me output as (2, -2 , -2) in gcc. I was expecting a positive result every time. Can a modulus be negative? Can anybody explain this behavior?
C99 requires that when a/b is representable:
(a/b) * b + a%b shall equal a
This makes sense, logically. Right?
Let's see what this leads to:
Example A. 5/(-3) is -1
=> (-1) * (-3) + 5%(-3) = 5
This can only happen if 5%(-3) is 2.
Example B. (-5)/3 is -1
=> (-1) * 3 + (-5)%3 = -5
This can only happen if (-5)%3 is -2
The % operator in C is not the modulo operator but the remainder operator.
Modulo and remainder operators differ with respect to negative values.
With a remainder operator, the sign of the result is the same as the sign of the dividend (numerator) while with a modulo operator the sign of the result is the same as the divisor (denominator).
C defines the % operation for a % b as:
a == (a / b * b) + a % b
with / the integer division with truncation towards 0. That's the truncation that is done towards 0 (and not towards negative inifinity) that defines the % as a remainder operator rather than a modulo operator.
Based on the C99 Specification: a == (a / b) * b + a % b
We can write a function to calculate (a % b) == a - (a / b) * b!
int remainder(int a, int b)
{
return a - (a / b) * b;
}
For modulo operation, we can have the following function (assuming b > 0)
int mod(int a, int b)
{
int r = a % b;
return r < 0 ? r + b : r;
}
My conclusion is that a % b in C is a remainder operation and NOT a modulo operation.
I don't think there isn't any need to check if the number is negative.
A simple function to find the positive modulo would be this -
Edit: Assuming N > 0 and N + N - 1 <= INT_MAX
int modulo(int x,int N){
return (x % N + N) %N;
}
This will work for both positive and negative values of x.
Original P.S: also as pointed out by #chux, If your x and N may reach something like INT_MAX-1 and INT_MAX respectively, just replace int with long long int.
And If they are crossing limits of long long as well (i.e. near LLONG_MAX), then you shall handle positive and negative cases separately as described in other answers here.
Can a modulus be negative?
% can be negative as it is the remainder operator, the remainder after division, not after Euclidean_division. Since C99 the result may be 0, negative or positive.
// a % b
7 % 3 --> 1
7 % -3 --> 1
-7 % 3 --> -1
-7 % -3 --> -1
The modulo OP wanted is a classic Euclidean modulo, not %.
I was expecting a positive result every time.
To perform a Euclidean modulo that is well defined whenever a/b is defined, a,b are of any sign and the result is never negative:
int modulo_Euclidean(int a, int b) {
int m = a % b;
if (m < 0) {
// m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
m = (b < 0) ? m - b : m + b;
}
return m;
}
modulo_Euclidean( 7, 3) --> 1
modulo_Euclidean( 7, -3) --> 1
modulo_Euclidean(-7, 3) --> 2
modulo_Euclidean(-7, -3) --> 2
The other answers have explained in C99 or later, division of integers involving negative operands always truncate towards zero.
Note that, in C89, whether the result round upward or downward is implementation-defined. Because (a/b) * b + a%b equals a in all standards, the result of % involving negative operands is also implementation-defined in C89.
According to C99 standard, section 6.5.5
Multiplicative operators, the following is required:
(a / b) * b + a % b = a
Conclusion
The sign of the result of a remainder operation, according
to C99, is the same as the dividend's one.
Let's see some examples (dividend / divisor):
When only dividend is negative
(-3 / 2) * 2 + -3 % 2 = -3
(-3 / 2) * 2 = -2
(-3 % 2) must be -1
When only divisor is negative
(3 / -2) * -2 + 3 % -2 = 3
(3 / -2) * -2 = 2
(3 % -2) must be 1
When both divisor and dividend are negative
(-3 / -2) * -2 + -3 % -2 = -3
(-3 / -2) * -2 = -2
(-3 % -2) must be -1
6.5.5 Multiplicative operators
Syntax
multiplicative-expression:
cast-expression
multiplicative-expression * cast-expression
multiplicative-expression / cast-expression
multiplicative-expression % cast-expression
Constraints
Each of the operands shall have arithmetic type. The
operands of the % operator shall have integer type.
Semantics
The usual arithmetic conversions are performed on the
operands.
The result of the binary * operator is the product of
the operands.
The result of the / operator is the quotient from
the division of the first operand by the second; the
result of the % operator is the remainder. In both
operations, if the value of the second operand is zero,
the behavior is undefined.
When integers are divided, the result of the / operator
is the algebraic quotient with any fractional part
discarded [1]. If the quotient a/b is representable,
the expression (a/b)*b + a%b shall equal a.
[1]: This is often called "truncation toward zero".
The result of Modulo operation depends on the sign of numerator, and thus you're getting -2 for y and z
Here's the reference
http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_14.html
Integer Division
This section describes functions for performing integer division.
These functions are redundant in the GNU C library, since in GNU C the
'/' operator always rounds towards zero. But in other C
implementations, '/' may round differently with negative arguments.
div and ldiv are useful because they specify how to round the
quotient: towards zero. The remainder has the same sign as the
numerator.
In Mathematics, where these conventions stem from, there is no assertion that modulo arithmetic should yield a positive result.
Eg.
1 mod 5 = 1, but it can also equal -4. That is, 1/5 yields a remainder 1 from 0 or -4 from 5. (Both factors of 5)
Similarly,
-1 mod 5 = -1, but it can also equal 4. That is, -1/5 yields a remainder -1 from 0 or 4 from -5. (Both factors of 5)
For further reading look into equivalence classes in Mathematics.
Modulus operator gives the remainder.
Modulus operator in c usually takes the sign of the numerator
x = 5 % (-3) - here numerator is positive hence it results in 2
y = (-5) % (3) - here numerator is negative hence it results -2
z = (-5) % (-3) - here numerator is negative hence it results -2
Also modulus(remainder) operator can only be used with integer type and cannot be used with floating point.
I believe it's more useful to think of mod as it's defined in abstract arithmetic; not as an operation, but as a whole different class of arithmetic, with different elements, and different operators. That means addition in mod 3 is not the same as the "normal" addition; that is; integer addition.
So when you do:
5 % -3
You are trying to map the integer 5 to an element in the set of mod -3. These are the elements of mod -3:
{ 0, -2, -1 }
So:
0 => 0, 1 => -2, 2 => -1, 3 => 0, 4 => -2, 5 => -1
Say you have to stay up for some reason 30 hours, how many hours will you have left of that day? 30 mod -24.
But what C implements is not mod, it's a remainder. Anyway, the point is that it does make sense to return negatives.
It seems the problem is that / is not floor operation.
int mod(int m, float n)
{
return m - floor(m/n)*n;
}
In a C program I was trying the below operations (Just to check the behavior)
x = 5 % (-3);
y = (-5) % (3);
z = (-5) % (-3);
printf("%d ,%d ,%d", x, y, z);
It gave me output as (2, -2 , -2) in gcc. I was expecting a positive result every time. Can a modulus be negative? Can anybody explain this behavior?
C99 requires that when a/b is representable:
(a/b) * b + a%b shall equal a
This makes sense, logically. Right?
Let's see what this leads to:
Example A. 5/(-3) is -1
=> (-1) * (-3) + 5%(-3) = 5
This can only happen if 5%(-3) is 2.
Example B. (-5)/3 is -1
=> (-1) * 3 + (-5)%3 = -5
This can only happen if (-5)%3 is -2
The % operator in C is not the modulo operator but the remainder operator.
Modulo and remainder operators differ with respect to negative values.
With a remainder operator, the sign of the result is the same as the sign of the dividend (numerator) while with a modulo operator the sign of the result is the same as the divisor (denominator).
C defines the % operation for a % b as:
a == (a / b * b) + a % b
with / the integer division with truncation towards 0. That's the truncation that is done towards 0 (and not towards negative inifinity) that defines the % as a remainder operator rather than a modulo operator.
Based on the C99 Specification: a == (a / b) * b + a % b
We can write a function to calculate (a % b) == a - (a / b) * b!
int remainder(int a, int b)
{
return a - (a / b) * b;
}
For modulo operation, we can have the following function (assuming b > 0)
int mod(int a, int b)
{
int r = a % b;
return r < 0 ? r + b : r;
}
My conclusion is that a % b in C is a remainder operation and NOT a modulo operation.
I don't think there isn't any need to check if the number is negative.
A simple function to find the positive modulo would be this -
Edit: Assuming N > 0 and N + N - 1 <= INT_MAX
int modulo(int x,int N){
return (x % N + N) %N;
}
This will work for both positive and negative values of x.
Original P.S: also as pointed out by #chux, If your x and N may reach something like INT_MAX-1 and INT_MAX respectively, just replace int with long long int.
And If they are crossing limits of long long as well (i.e. near LLONG_MAX), then you shall handle positive and negative cases separately as described in other answers here.
Can a modulus be negative?
% can be negative as it is the remainder operator, the remainder after division, not after Euclidean_division. Since C99 the result may be 0, negative or positive.
// a % b
7 % 3 --> 1
7 % -3 --> 1
-7 % 3 --> -1
-7 % -3 --> -1
The modulo OP wanted is a classic Euclidean modulo, not %.
I was expecting a positive result every time.
To perform a Euclidean modulo that is well defined whenever a/b is defined, a,b are of any sign and the result is never negative:
int modulo_Euclidean(int a, int b) {
int m = a % b;
if (m < 0) {
// m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
m = (b < 0) ? m - b : m + b;
}
return m;
}
modulo_Euclidean( 7, 3) --> 1
modulo_Euclidean( 7, -3) --> 1
modulo_Euclidean(-7, 3) --> 2
modulo_Euclidean(-7, -3) --> 2
The other answers have explained in C99 or later, division of integers involving negative operands always truncate towards zero.
Note that, in C89, whether the result round upward or downward is implementation-defined. Because (a/b) * b + a%b equals a in all standards, the result of % involving negative operands is also implementation-defined in C89.
According to C99 standard, section 6.5.5
Multiplicative operators, the following is required:
(a / b) * b + a % b = a
Conclusion
The sign of the result of a remainder operation, according
to C99, is the same as the dividend's one.
Let's see some examples (dividend / divisor):
When only dividend is negative
(-3 / 2) * 2 + -3 % 2 = -3
(-3 / 2) * 2 = -2
(-3 % 2) must be -1
When only divisor is negative
(3 / -2) * -2 + 3 % -2 = 3
(3 / -2) * -2 = 2
(3 % -2) must be 1
When both divisor and dividend are negative
(-3 / -2) * -2 + -3 % -2 = -3
(-3 / -2) * -2 = -2
(-3 % -2) must be -1
6.5.5 Multiplicative operators
Syntax
multiplicative-expression:
cast-expression
multiplicative-expression * cast-expression
multiplicative-expression / cast-expression
multiplicative-expression % cast-expression
Constraints
Each of the operands shall have arithmetic type. The
operands of the % operator shall have integer type.
Semantics
The usual arithmetic conversions are performed on the
operands.
The result of the binary * operator is the product of
the operands.
The result of the / operator is the quotient from
the division of the first operand by the second; the
result of the % operator is the remainder. In both
operations, if the value of the second operand is zero,
the behavior is undefined.
When integers are divided, the result of the / operator
is the algebraic quotient with any fractional part
discarded [1]. If the quotient a/b is representable,
the expression (a/b)*b + a%b shall equal a.
[1]: This is often called "truncation toward zero".
The result of Modulo operation depends on the sign of numerator, and thus you're getting -2 for y and z
Here's the reference
http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_14.html
Integer Division
This section describes functions for performing integer division.
These functions are redundant in the GNU C library, since in GNU C the
'/' operator always rounds towards zero. But in other C
implementations, '/' may round differently with negative arguments.
div and ldiv are useful because they specify how to round the
quotient: towards zero. The remainder has the same sign as the
numerator.
In Mathematics, where these conventions stem from, there is no assertion that modulo arithmetic should yield a positive result.
Eg.
1 mod 5 = 1, but it can also equal -4. That is, 1/5 yields a remainder 1 from 0 or -4 from 5. (Both factors of 5)
Similarly,
-1 mod 5 = -1, but it can also equal 4. That is, -1/5 yields a remainder -1 from 0 or 4 from -5. (Both factors of 5)
For further reading look into equivalence classes in Mathematics.
Modulus operator gives the remainder.
Modulus operator in c usually takes the sign of the numerator
x = 5 % (-3) - here numerator is positive hence it results in 2
y = (-5) % (3) - here numerator is negative hence it results -2
z = (-5) % (-3) - here numerator is negative hence it results -2
Also modulus(remainder) operator can only be used with integer type and cannot be used with floating point.
I believe it's more useful to think of mod as it's defined in abstract arithmetic; not as an operation, but as a whole different class of arithmetic, with different elements, and different operators. That means addition in mod 3 is not the same as the "normal" addition; that is; integer addition.
So when you do:
5 % -3
You are trying to map the integer 5 to an element in the set of mod -3. These are the elements of mod -3:
{ 0, -2, -1 }
So:
0 => 0, 1 => -2, 2 => -1, 3 => 0, 4 => -2, 5 => -1
Say you have to stay up for some reason 30 hours, how many hours will you have left of that day? 30 mod -24.
But what C implements is not mod, it's a remainder. Anyway, the point is that it does make sense to return negatives.
It seems the problem is that / is not floor operation.
int mod(int m, float n)
{
return m - floor(m/n)*n;
}
I am having an issue with the % operator in C. I know that the % operator gives the remainder of a division. However when faced with a question like 1 % 2 or 3 % 2, I get confused. After googling this, I found different solutions.
Some say that as 1 / 2 is 0.5, we round it down to 0. So 1 % 2 is 0.
Others say that as 1 / 2 is 0.5, we instead round it up, like we would in maths, to 1. So 1 % 2 is 1.
And therefore, I am now confused. My question is: What is 1 % 2?
Thank you in advance :):)
% is the remainder operator:
The % operator computes the remainder after dividing its first operand
by its second.
It's what left from the division. For example:
5 % 3 is 2.
5 % 4 is 1.
5 % 2 is 1. (Because 2 can fit 2 times in 5, 1 will be left)
When you do 1 % 2 the result is 1 because 1/2 is 0, and the remainder is.. 1.
Simply put, both are wrong methods. As you said % finds the remainder of division.
Therefore 1/2 is equal to 0 remainder 1.
And the answer is thus 1.
Also, to experiment yourself, you could have used this program:
#include <stdio.h>
main()
{
int remainder;
remainder = 1 % 2;
printf("1 %% 2 is %d", remainder);
return(0);
}
Hope this helps :)
The easy way to think of M % D (if both M and D are positive) is:
While ( M >= D){
M = M-D;
}
return M;
There is no rounding, the decimal part is simply truncated.
So, 1 / 2 is 0 and 1 % 2 is 1.
Here you need the mathematical definition on remainder.
Given two integer numbers m, d, we say that r is the remainder of the division of m and d if r satisfies two conditions:
There exists another integer k such that m == k * d + r , and
0 <= r < d.
In C we have m % d == r and m / d == k, just by following the definition above.
As you can see, there is no trucation at all (I mean: the "truncation" is consequence of the definition).
From the definition, it can be obtainded that 3 % 2 == 1 and 3 / 2 == 1.
Other examples:
4 / 3 == 1 and 5 / 3 == 1, in despite of 5.0/3.0 == 1.6666 (which
would round to 2.0).
4 % 3 == 1 and 5 % 3 == 2.
You can trust also in the formula r = m - k * d, which in C is written as:
m % d == m - (m / d) * d
However, in the standard C, the integer division follows the rule: round to 0.
Thus, with negative operands C offer different results that the mathematical ones.
We would have:
(-4) / 3 == -1, (-4) % 3 == -1 (in C), but in plain maths: (-4) / 3 = -2, (-4) % 3 = 2.
In plain maths, the remainder is always nonnegative, and less than the abs(d).
In standard C, the remainder always has the sign of the first operator.
Remark: This description (in the negative case) is for standard C99/C11 only. You must be carefull with your compiler version, and to do some tests.
In this case, what does the percentage refers to?
int myInt = 27 % 10;
myInt = 7;
What does the % mean in this code?
% means remainder, when 27 is divided by 10 leaves a remainder 7
EDIT:
My 2 cents about all the discussion about difference between modulo & remainder
Take a % b
1. When both +ve, Modulo & Remainder are one and the same
2. When a is -ve, they are not the same
For example;
a = -10, b = 3
Remainder of -10 % 3 = -1
for Modulo, add a greater multiple of 3 to your 'a' and calculate the remainder.
-10 + 12 = 2
2 % 3 = 2 is your answer
the % is modulus operator, not percentage. For percentage, you just do regular math. 50% is to multiply by .5... etc.
For future reference, the objective c mathematical operations are documented many places, including here.
Note the % is called "Modulo" operator.
% is a operator to find the remainder of a division.
The "%" in this code is called the modulus operator. This causes the processor to perform a division operation, and it returns the remainder of the division.
For example:
8 % 10 = 8
5 % 4 = 1
In a C program I was trying the below operations (Just to check the behavior)
x = 5 % (-3);
y = (-5) % (3);
z = (-5) % (-3);
printf("%d ,%d ,%d", x, y, z);
It gave me output as (2, -2 , -2) in gcc. I was expecting a positive result every time. Can a modulus be negative? Can anybody explain this behavior?
C99 requires that when a/b is representable:
(a/b) * b + a%b shall equal a
This makes sense, logically. Right?
Let's see what this leads to:
Example A. 5/(-3) is -1
=> (-1) * (-3) + 5%(-3) = 5
This can only happen if 5%(-3) is 2.
Example B. (-5)/3 is -1
=> (-1) * 3 + (-5)%3 = -5
This can only happen if (-5)%3 is -2
The % operator in C is not the modulo operator but the remainder operator.
Modulo and remainder operators differ with respect to negative values.
With a remainder operator, the sign of the result is the same as the sign of the dividend (numerator) while with a modulo operator the sign of the result is the same as the divisor (denominator).
C defines the % operation for a % b as:
a == (a / b * b) + a % b
with / the integer division with truncation towards 0. That's the truncation that is done towards 0 (and not towards negative inifinity) that defines the % as a remainder operator rather than a modulo operator.
Based on the C99 Specification: a == (a / b) * b + a % b
We can write a function to calculate (a % b) == a - (a / b) * b!
int remainder(int a, int b)
{
return a - (a / b) * b;
}
For modulo operation, we can have the following function (assuming b > 0)
int mod(int a, int b)
{
int r = a % b;
return r < 0 ? r + b : r;
}
My conclusion is that a % b in C is a remainder operation and NOT a modulo operation.
I don't think there isn't any need to check if the number is negative.
A simple function to find the positive modulo would be this -
Edit: Assuming N > 0 and N + N - 1 <= INT_MAX
int modulo(int x,int N){
return (x % N + N) %N;
}
This will work for both positive and negative values of x.
Original P.S: also as pointed out by #chux, If your x and N may reach something like INT_MAX-1 and INT_MAX respectively, just replace int with long long int.
And If they are crossing limits of long long as well (i.e. near LLONG_MAX), then you shall handle positive and negative cases separately as described in other answers here.
Can a modulus be negative?
% can be negative as it is the remainder operator, the remainder after division, not after Euclidean_division. Since C99 the result may be 0, negative or positive.
// a % b
7 % 3 --> 1
7 % -3 --> 1
-7 % 3 --> -1
-7 % -3 --> -1
The modulo OP wanted is a classic Euclidean modulo, not %.
I was expecting a positive result every time.
To perform a Euclidean modulo that is well defined whenever a/b is defined, a,b are of any sign and the result is never negative:
int modulo_Euclidean(int a, int b) {
int m = a % b;
if (m < 0) {
// m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
m = (b < 0) ? m - b : m + b;
}
return m;
}
modulo_Euclidean( 7, 3) --> 1
modulo_Euclidean( 7, -3) --> 1
modulo_Euclidean(-7, 3) --> 2
modulo_Euclidean(-7, -3) --> 2
The other answers have explained in C99 or later, division of integers involving negative operands always truncate towards zero.
Note that, in C89, whether the result round upward or downward is implementation-defined. Because (a/b) * b + a%b equals a in all standards, the result of % involving negative operands is also implementation-defined in C89.
According to C99 standard, section 6.5.5
Multiplicative operators, the following is required:
(a / b) * b + a % b = a
Conclusion
The sign of the result of a remainder operation, according
to C99, is the same as the dividend's one.
Let's see some examples (dividend / divisor):
When only dividend is negative
(-3 / 2) * 2 + -3 % 2 = -3
(-3 / 2) * 2 = -2
(-3 % 2) must be -1
When only divisor is negative
(3 / -2) * -2 + 3 % -2 = 3
(3 / -2) * -2 = 2
(3 % -2) must be 1
When both divisor and dividend are negative
(-3 / -2) * -2 + -3 % -2 = -3
(-3 / -2) * -2 = -2
(-3 % -2) must be -1
6.5.5 Multiplicative operators
Syntax
multiplicative-expression:
cast-expression
multiplicative-expression * cast-expression
multiplicative-expression / cast-expression
multiplicative-expression % cast-expression
Constraints
Each of the operands shall have arithmetic type. The
operands of the % operator shall have integer type.
Semantics
The usual arithmetic conversions are performed on the
operands.
The result of the binary * operator is the product of
the operands.
The result of the / operator is the quotient from
the division of the first operand by the second; the
result of the % operator is the remainder. In both
operations, if the value of the second operand is zero,
the behavior is undefined.
When integers are divided, the result of the / operator
is the algebraic quotient with any fractional part
discarded [1]. If the quotient a/b is representable,
the expression (a/b)*b + a%b shall equal a.
[1]: This is often called "truncation toward zero".
The result of Modulo operation depends on the sign of numerator, and thus you're getting -2 for y and z
Here's the reference
http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_14.html
Integer Division
This section describes functions for performing integer division.
These functions are redundant in the GNU C library, since in GNU C the
'/' operator always rounds towards zero. But in other C
implementations, '/' may round differently with negative arguments.
div and ldiv are useful because they specify how to round the
quotient: towards zero. The remainder has the same sign as the
numerator.
In Mathematics, where these conventions stem from, there is no assertion that modulo arithmetic should yield a positive result.
Eg.
1 mod 5 = 1, but it can also equal -4. That is, 1/5 yields a remainder 1 from 0 or -4 from 5. (Both factors of 5)
Similarly,
-1 mod 5 = -1, but it can also equal 4. That is, -1/5 yields a remainder -1 from 0 or 4 from -5. (Both factors of 5)
For further reading look into equivalence classes in Mathematics.
Modulus operator gives the remainder.
Modulus operator in c usually takes the sign of the numerator
x = 5 % (-3) - here numerator is positive hence it results in 2
y = (-5) % (3) - here numerator is negative hence it results -2
z = (-5) % (-3) - here numerator is negative hence it results -2
Also modulus(remainder) operator can only be used with integer type and cannot be used with floating point.
I believe it's more useful to think of mod as it's defined in abstract arithmetic; not as an operation, but as a whole different class of arithmetic, with different elements, and different operators. That means addition in mod 3 is not the same as the "normal" addition; that is; integer addition.
So when you do:
5 % -3
You are trying to map the integer 5 to an element in the set of mod -3. These are the elements of mod -3:
{ 0, -2, -1 }
So:
0 => 0, 1 => -2, 2 => -1, 3 => 0, 4 => -2, 5 => -1
Say you have to stay up for some reason 30 hours, how many hours will you have left of that day? 30 mod -24.
But what C implements is not mod, it's a remainder. Anyway, the point is that it does make sense to return negatives.
It seems the problem is that / is not floor operation.
int mod(int m, float n)
{
return m - floor(m/n)*n;
}