why are we doing
for(int i = 0 ; i< n , i++){
int x ; cin >> x ;
sum =(sum+x + mod) % mod //mod is 10e9 + 7
and then again taking modulo at each queries, i understand that for each query we need to do that but why for the initial sum ?

The initial sum can be as large as 10^{14}. So, taking modulo is not necessary for the initial sum, but as a good practice people do it - it reduces the computational time a bit since the numbers do not exceed 10^{9} + 7.

but i am getting WA if i dont take modulo in the initial sum

That could be because the sum can be as small as -10^{14} (it is negative). So, this statement doesn’t work.

mod = 1e9 + 7;
sum = -100000000000000; // -1e14
sum %= mod; // Line 3
// sum will be negative

// Instead write it as:
sum = (sum % mod + mod) % mod;

This is the correct way I guess.

Edit: Sum will not be negative at line 3. Seems there is some other reason for WA.

@ssjgz may help.

Edit 2: I am unable to understand its behaviour.

C Code
#include <stdio.h>
typedef long long int ll;
int main() {
    ll sum = -(1e14);
    ll mod = (1e9 + 7);
    printf("%lld %lld\n", sum, mod);
    printf("%lld\n", sum % mod);
    return 0;


-100000000000000 1000000007
Python Code
s = -(10**14)
mod = 10**9 + 7
print(s % mod)


1 Like

i am also not being able to understand why it is so :thinking:

You can try these modulo operators
int add(int a,int b){a%=mod,b%=mod;a=((a+b)%mod+mod)%mod;return a;}
int sub(int a,int b){a%=mod,b%=mod;a=((a-b)%mod+mod)%mod;return a;}
int mul(int a,int b){a%=mod,b%=mod;a=((a*b)%mod+mod)%mod;return a;}

Modulo operator of Python is different from C/C++ , it will always return output having same sign as divisor.