This might super dumb to ask ,but I really need some clear cut answer to this nightmare of mine
Due to this one operation I lost confidence even in questions that I am capable of solving and many Wrong Submissions during the contests where I am having trouble to use this mod (sounds stupid)
Just a simple question....
WHEN & WHERE(i.e in which part of the code) DO I NEED TO USE (% MOD)?
Are there any golden rules on where to use %mod
Also what is the guarantee (or any proof kinda thing) that using %mod at a particular place do not change my final answer??








you can use it always with * and +. (a — b) % mod => (a%mod — b%mod + mod)%mod
be careful with -, since it is not just (a — b) % mod. Because a — b might be less than zero
So any proof that using %mod at * , + == final_answer_without_mod%mod
Or is it just '%' obeys distributive property with +,* ?
If x >= mod, you must use x%mod, but if x < mod, x%mod == x and nothing would be changed, so you always can use %. And I suggest using % always, not only in the end, as it can prevent owelflow
It's ok bro. I'm scared of it too
Use a modulo integer class
Thanks for the suggestion
Use modint as suggested by Mindeveloped, or write functions that apply mod for you and use them everywhere for your calculation. This can be better if you're going to offline competitions where you don't have a modint template at hand.
Example:
Thanks, having a class modint makes it less time consuming and less error prone
yes this is what i need to do better in offline competition
Using something like
might help, instead of using
+,-,*and/to perform the operations safely. (/is mostly just useless in case of modular operations)(I know the above code applies
Modtoo many times and might increase overhead but I just like to keep the functions safe for big or negative inputs unless the time limit is too strict)Additionally, avoid using
intfor variables that store modular values, as multiplication (or addition or subtraction) with big numbers can cause overflow.As for when and where to apply
%, you want to apply it after any operation whose result can be >=mod. If you use the*operator, make sure you don't do more than one multiplication (or addition or subtraction) without modding the previous result. For example,Also, in case of negative numbers (like result of a subtraction), make sure you you add
modifres % modreturns a negative number.However if you just use the functions given above, you don't have to pay too much attention to these details.
There might be other ways like using a modular integer class, but this is just what I'm comfortable with. Hope it helps!
I think the title is a bit rude