[closed] MOD of negative nos

,

how to calc mod of negative nos?

…to make it non-negative first by adding MOD…

for example -12 mod 5 = -7 mod 5 = -2 mod 5 = 3 mod 5 = 3

2 Likes

while(number < 0)
{
number = number + MOD
}

Insert this code , where you think number becomes negative . Then you can easily take mod as number = number%MOD.

3 Likes

take its mod like you take mod of any positive number, but at the end add mod to this result to get the final answer.

eg -12mod5=-2
-2+5=3

2 Likes

suppose i have MOD=5
and num=-16
if i calculate ans as ans=num%MOD
it gives -1
but your approach gives 4
whats the difference?

2 WA cause of this , didn’t read the constraint on elements :frowning:

1 Like

me too, don’t worry, 7 submits for such easy problem, setter got me :frowning: my fault…

2 Likes

Also faced this problem in the cook-53, there are so many things I don’t know!! :’(

You really don’t have to worry about negative no.s or what.
Computer does that job.

e.g.
-2 % 5 = 3

2 % 5 = 2

We can use " ans = (mod + number mod) mod " for both negative and positive number

1 Like

Do we need to do it manually?
that adding MOD thing?

No, @void_pointer is correct - ans = (mod + number % mod) % mod works fine, but if you are not formula guy, you can achieve it manually…

Or when |A| <= 100, you can simply do num + 100 * MOD

1 Like

thanx @betlista got AC now

You may use this function,

int mod(num ,modValue)
{
    return ( modValue- ( (-num) % modValue) );
}

i think it depends how negative mod is defined