In divisible subarrays?

in divisible sum array problems code ?

can I skip " sum%=n;"
as after this line sum=(sum+n)%n; line is used which will work for both negative and positive no.

we have written
sum+=arr[I]; and we are also updating our sum by doing sum%=n; then when the loop runs for the second time we don’t have the previous sum which is needed

@mehulbhandari358
You cannot slip the first part as, let’s take an example
a = - 5 n = 3
If you add 3 to it, it’s still a negative number. So you may need to add 3 a few times. We don’t know how many times it’ll be needed
SO doing %n first reduced the range, and it will ensure that adding n only once will make the number positive, which will in turn make its mod positive

I don’t understand your second doubt, where is the previous sum needed?

how will be know how much range is reduded as it is negative .
in positive no. range is 0,1,2…n-1

we are not making the prefix sum array as we just want modulus so we have to find the sum right ? thats why we are doing sum%=n; ?

hope you are clear about my doubt

@mehulbhandari358 it will be reduced just enough that when you add N again, the number will become positive no matter what, you can take examples and see

@mehulbhandari358 if you are having any confusion because of the sum variable you can make a prefix sum array also, this is just more space efficient

no i dont want to use prefix sum ? please clear my confusion –
first we are doing sum+=a[i];
then we are updating it sum%=n because of which we dont have the previous sum…

@mehulbhandari358 why would you need the previous sum? You only need the mod part for your calculations to make the frequency map and get the final answer

yes you are correct the only thing which we need here is mod part but we have to take out mod of the prefix sum array right ? because of that we need the previous sum .

@mehulbhandari358 actually we don’t, because of properties of MOD.

please explain me in details . which mod property are you talking about?

@mehulbhandari358 please do a dry run once, and let me know if you still have any doubts. I think it should become clear if you dry run

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.