# [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

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

You may use this function,

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

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

2 WA cause of this , didnâ€™t read the constraint on elements

1 Like

me too, donâ€™t worry, 7 submits for such easy problem, setter got me my faultâ€¦

2 Likes

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

Do we need to do it manually?
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`