Regarding modulo operation for negative numbers

I cant understand how sir used the modulo operation to handle the case when sum gets negative.
Please provide the detailed explanation with examples.
reply as soon as possible.

@D19APPPP0016 lets take an example

let a = 5 and n = 3
a%n = 2

if a = -5, n = 3
a%n = (a+n)%n
ie, (-5+3)%3 = (-2+3)%3 = 1%3 = 1

this equation works even if a is positive
a = 5, n = 3
a%n = (a+n)%n
ie (5+3)%3 = 8%3 = 2

Is it clear now?

but (-5+3)%3=(-2)%3 how are u taking it to be 2%3.

reply fast as soon as possible

@D19APPPP0016
Sorry for the inconvenience caused! That was a very silly mistake on my part.

Let’s take example of a=-5 n=3 again
now to make A positive, 3 needs to be added 2 times, ie - 5 + 6 = 1
And 1%3 = 1

And that is the answer we need.
Think of it like this, if we divide -5 by 3, we are short by 1 number to get - 6 to be perfectly divisible by 3
Comparing it with a positive number,

If n = 8, we are short by 2 to get 6.

By “short” i mean that if we subtract this number from A, we’ll get a multiple of n

SO - 5 - 1 = 6, hence - 5%3=1
8-2=6 hence 8%6 = 2

I hope everything is clear now.

We basically do all this to avoid a negative answer and get all the answers in the range of [0,n)

Can u explain all of this with the operation used in this video. It would be really helpful as i am getting confused with this.

@D19APPPP0016

  1. take input for array
  2. make a cumulative sum array
  3. take mod of the cumulative sum to bring all the elements in the range [0,n)
  4. now make a frequency array of size n, storing frequencies of all elements from 0 to n
  5. calculate final answer, by the simple nCr formula, ie where n = size of array, r = 2
  6. add answer for all frequencies
  7. print the final answer

as u mentioned that sometimes number needed to be added twice to make it positive as in case of a=-5 and n=3 but here sir is adding number only once . Then how will it become positive. Explain.

@D19APPPP0016 we took mod without adding n first, so range is reduced, then we take mod again, this time by adding n

Can u explain these two lines sum%=n ; sum=(sum+n)%n; with the a=-5 and n=3

@D19APPPP0016
a = -5, n = 3
take normal mod first, a%n
a becomes -2 (you can verify this by a simple cout statement in IDE)
now do (a+n)%n
(-2 + 3)%3 = 1%3 = 1

Thanks for entertaining my doubts , got it.

1 Like

@D19APPPP0016 please mark the doubt as resolved if all your queries have been cleared :slight_smile: