Why would you ever add 10^9+7 to a number and then take mod with 10^9+7

118 Views Asked by At

I was solving a problem of Fenwick tree named shill and wave sequence and it wasn't passing all the test cases until I added a line looking at the solution and now want to find its purpose ,here is my code

#include<bits/stdc++.h>
using namespace std;
#define mod 1000000007
long long query(long long index,int p,long long **bit)
{
    long long count=0;
    for(;index>0;index-=(index&(-index)))
    {
        count=(count+bit[index][p])%mod;
    }
    return count;
}
void update(long long **bit,long long index,int p,long long val)
{
    for(;index<=100000;index+=(index&(-index)))
    {
        bit[index][p]=(bit[index][p]+val)%mod;
    }
}

int main()
{
    int n;
    cin>>n;
    long long ans=0;
    long long **bit=new long long*[100000+1];
    for(int i=1;i<=100000;i++)
    {
        bit[i]=new long long[3];
        for(int j=0;j<3;j++)
        {
            bit[i][j]=0;
        }
    }
    for(int i=0;i<n;i++)
    {
        long long x;
        cin>>x;
        long long a=(query(x-1,0,bit)+query(x-1,2,bit))%mod;
        long long b=(query(100000,1,bit)+query(100000,2,bit))%mod-query(x,1,bit)-query(x,2,bit);
        b=(b+mod)%mod;
//WHAT IS THE PURPOSE OF ABOVE LINE?
        ans+=(a+b)%mod;
        update(bit,x,0,b);
        update(bit,x,1,a);
        update(bit,x,2,1);
    }
    cout<<ans%mod;
    return 0;
} 

b=(b+mod)%mod but why?

2

There are 2 best solutions below

3
user32149 On

The "purpose" of the line (or rather, the reason that it has any effect) could be that

b=(b+mod)%mod;

changes the value of b.

So the remaning question is, does it matter that you add "mod" before applying %mod?

Mathematically speaking

(x+y) mod y = x mod y

However, in many programming languages, there is a maximum value of int and if you add up something too big, you get an integer overflow. In that case, it can easily happen that

(x+y) mod y != x mod y

which could be the case for you.

2
ksohan On

For some cases b can be negative and may cause incorrect results while doing % directly. That's why before doing % operation it's safe to add mod and then do % which will make the number positive first and then do the modulo.