icode_8990's blog

By icode_8990, history, 5 years ago, In English

Hello, Newbie here. I am trying to solve this problem and this is the solution i am referring to:

#include<bits/stdc++.h>
using namespace std;
#define mod 1000000007
long long num[100010],pw[100010];
int main()
{
	long long n,q,i,res,l,r;
	string s;
	cin>>n>>q;
	cin>>s;
	for(i=0;i<n;i++)
	{
		num[i+1] =num[i]+(s[i]=='0');
	}
	pw[0]=1;
	for(i=1;i<n+5;i++)
	{
		pw[i] = pw[i-1]*2;
		if(pw[i]>=mod) pw[i]-=mod;
	}
	while(q--)
	{
		scanf("%lld%lld",&l,&r);
		res=(mod+pw[r-l+1]-pw[num[r]-num[l-1]])%mod; 
		printf("%lld\n",res);
	}

	
	return 0;
}

I am trying to understand the modulo used here. why does he add another mod in res. How does it help?

Thanks!

  • Vote: I like it
  • +3
  • Vote: I do not like it

»
5 years ago, # |
  Vote: I like it 0 Vote: I do not like it

It's so that if it goes negative, it will be rectified.

»
5 years ago, # |
  Vote: I like it 0 Vote: I do not like it

C++ % operator is undefined behavior with negative number (depends on compiler). Adding mod keeps it positive while maintaining the answer.