MATBREAK- APRIL COOKOFF

Can anyone please Explain what is wrong in my code it is not excepted by judge but the output is correct as per the TEST CASE
#include<bits/stdc++.h>
using namespace std;
#define N 1000000007

long long int myexp(long long int base,
long long int exp)
{
if (exp == 0)
return 1;
if (exp == 1)
return base % N;
long long int t = myexp(base, exp / 2);
t = (t * t) % N;
if (exp % 2 == 0)
return t;
else
return ((base % N) * t) % N;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t–)
{
long long int n, a;
cin >> n >> a;
long long int sum = 0;
int count = 1;
for (int i = 0; i < n; i++)
{
long long int d = (myexp(a, count)) % N;
sum += d%N ;
a *= d;
count += 2;
}
cout << sum%N << endl;
}
}

@codie_1
sum += d%N ;
a *= d;
Change these lines to these
sum =(sum+ d)%N ; a =(a * d)%N;

1 Like

Thanks It Worked can U explain Me the logic behind as much i know both are same

sum+=d%N will evaluate d%N first and add it to sum, this might cause an overflow. So we perform (sum + d) % N
Same logic applies for the second line.

@codie_1 as @rajdeep14 said…
sum+=d%N will be equated as sum = sum +d%N
but we do not want this to happen as it will cause an overflow. What we want to do is
sum = (sum + d)%N.
I was also making the same mistake. I learnt that whenever we have to take a modulus by something in an equation, it’s better to avoid using a shorthand notation.

1 Like

@prog_am_er and @rajdeep14 Thanks for the Explaination

1 Like