viernes, 27 de mayo de 2016

Operador modulo con numeros negativos


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 bmodN, just keep adding N to b until the number is between 0 and N.
As an example, N=13,b=27. Add 13 to -27, you get -14, again you get -1, and again you get 12.
So, 27mod13=12.
A bit more generally, you might want to realize that amodN=a+kNmodN for any kN. That should help with your first question.
***************
A encontrar bmodN, sólo mantenga la adición de N a b hasta que el número está entre 0 y N.

Como un ejemplo, N=13,b=27. Añadir 13 a -27, consigue -14, de nuevo usted obtiene -1, y de nuevo consigue 12.

Así, 27mod13=12.

Un poco más generalmente, usted podría querer darse cuenta de que amodN=a+kNmodN para kN. 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