Блог пользователя dhanunjaygurram12340

Автор dhanunjaygurram12340, история, 14 месяцев назад, По-английски

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??

  • Проголосовать: нравится
  • +8
  • Проголосовать: не нравится

»
14 месяцев назад, скрыть # |
Rev. 2  
Проголосовать: нравится 0 Проголосовать: не нравится

you can use it always with * and +. (a — b) % mod => (a%mod — b%mod + mod)%mod

»
14 месяцев назад, скрыть # |
 
Проголосовать: нравится +9 Проголосовать: не нравится

It's ok bro. I'm scared of it too

»
14 месяцев назад, скрыть # |
 
Проголосовать: нравится +3 Проголосовать: не нравится

Use a modulo integer class

»
14 месяцев назад, скрыть # |
Rev. 2  
Проголосовать: нравится +4 Проголосовать: не нравится

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.

Spoiler

Example:

dp[i] = add(dp[i], mul(dp[i-1], dp[i-2]));
»
14 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Using something like

This

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 Mod too 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 int for 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,

Spoiler

Also, in case of negative numbers (like result of a subtraction), make sure you you add mod if res % mod returns 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!

»
14 месяцев назад, скрыть # |
 
Проголосовать: нравится +4 Проголосовать: не нравится

I think the title is a bit rude