Weird behaviour on HackerRank?

Can anyone explain this weird behavior ??
(correct one has accepted submission)

problem Sherlock and Permutations | HackerRank

why this line is wrong
((fact[n] % mod) * ((mul[k] % mod) * (mul[n - k] % mod)) % mod) % mod;
submission https://www.hackerrank.com/challenges/sherlock-and-permutations/copy-from/177307265

and this is correct
(fact[n] % mod * (mul[k] % mod * mul[n - k] % mod) % mod) % mod;
submission https://www.hackerrank.com/challenges/sherlock-and-permutations/copy-from/177308369

while in this problem Summing the N series | HackerRank

this is correct
((n % mod) * (n % mod)) % mod
submission https://www.hackerrank.com/challenges/summing-the-n-series/copy-from/177301822

and this is wrong
(n % mod * n % mod) % mod
submission https://www.hackerrank.com/challenges/summing-the-n-series/copy-from/177301360

I only applied the bracket to make it cleaner.
is the problem on their side ??

For the latter two:

2 Likes

then ((n % mod) * (n % mod)) % mod this should be correct right??
it is more precise and describes what has been done and I always apply proper bracket since when not applied unexpected results occur.
so I was expecting more bracket one to be a correct one.

hey so why in above case using proper bracket does not give right answer as in second one.

Your more brackets makes it more correct logic is incorrect.
((mul[k] % mod) * (mul[n - k] % mod))
This will give a value that is less than mod*mod.
It will then get multiplied by fac[n]%mod, and then the 2 outer mods will happen, also that means the outer mod is useless. The fact the second one got AC, implies mul[k] and mul[n-k] are less than mod.

Because then we are doing mul[k]%mod * mul[n-k], and then taking mod, so the bracket’s value will be less than mod, and then will get multiplied by fac[n]%mod, and then we will take modulo twice. So it won’t overflow.

Also whatever code you’ve written is absolutely revolting. Do not put so many brackets and mods, it becomes hard to parse them while just looking through them.
fac[n] * mul[k] %mod * mul[n-k] %mod is enough here.

Mod has as much priority as multiplication, and therefore is done from left to right unless there is brackets.

In the second code, it is easy to see that n>=mod, so the first code is correct. because you need to take mod to multiply, and then take mod again to fix the result. If it’s possible to take n%=mod, you should so that first. Since the answer is a polynomial, you can take n%=mod, so it would have then n*n%mod.

The only time you cannot take n%=mod, is when n is in the exponent.

1 Like

thanks man. I saw my first one logic with more bracket was incorrect, as * and % have the same priority so equation is evaluated from left to right which will lead to overlflow in my equation.
man I never knew about the priority of % and *.