I have been practicing taking modulo for answers but not understanding when to add mod and when to substract it from the answer.

for e.g. ans=(ans-1+mod)%mod;

why it is so?

Remember that the answer is expected to be from 0 to mod-1 (inclusive) but the modulus operator ("%") doesnâ€™t guarantee this.

For example, (-12 % 10) == -2, which is not what we want.

We would have to add twice the modulus to get our answer in the correct range:

(-12 + 2*10) % 10 == 8 (as expected)