1
|
The Quickest and easiest way to find the mod of a negative number is by using the below property
if a = (b) mod c then a = (c*k + b) mod c (where k = 1,2,3.......) It simply says that the value of a is unchanged when we add a multiple of c to b
Example
a = (10) mod 3 we all know that a = 1 Now
a = (3*1 + 10) mod 3 - a is still = 1
a = (3*2 + 10) mod 3 - a is still = 1
a = (3*3 + 10) mod 3 - a is still = 1
a = (3*4 + 10) mod 3 - a is still = 1
So adding any multiple of 3 (> 0) to 10 does not effect the value of a Now we use this to our advantage in finding mod of negative numbers
Example
a = (-10) mod 3 Now i add 12 to 10 as 12 is a multiple of 3 and hence the value of a will remain unchanged
so a = (3*4 – 10) mod 3 = 2 mod 3 = 2
easy isnt it?
Another example
a = (-340) mod 60 So a = (60*6 – 340) mod 60 = (360-340) mod 60 = 20 mod 60 = 20
|
To find , just keep adding to until the number is between 0 and .
As an example, . Add 13 to -27, you get -14, again you get -1, and again you get 12.
So, .
A bit more generally, you might want to realize that for any . That should help with your first question.
***************
A encontrar , sólo mantenga la adición de a hasta que el número está entre 0 y .
Como un ejemplo, . Añadir 13 a -27, consigue -14, de nuevo usted obtiene -1, y de nuevo consigue 12.
Así, .
Un poco más generalmente, usted podría querer darse cuenta de que para . Eso debería ayudar con tu primera pregunta.
***************
Como un ejemplo, . Añadir 13 a -27, consigue -14, de nuevo usted obtiene -1, y de nuevo consigue 12.
Así, .
Un poco más generalmente, usted podría querer darse cuenta de que para . Eso debería ayudar con tu primera pregunta.
***************
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:
int mod(int a, int b)
{
int r = a % b;
return r < 0 ? r + b : r;
}
My conclusion is (a % b) in C is a remainder operator and NOT modulo operator.
No hay comentarios:
Publicar un comentario