MATBREAK ;WA is coming


using namespace std;

typedef long long ll;

ll mod=1e9+7;

ll exp(ll a, ll n){

    if(n==0)

        return 1;

    if(n==1)

        return a;

    ll r = exp(a, n / 2) % mod;

    

    if (n % 2 == 0)

        return (r * r) % mod;

    else 

        return (r * r * a) % mod;

  

}

int main(){

   // ll m = pf(20, 4);

   // cout<<m<<"\n";

        ll t;

        cin>>t;

        while(t--){

        ll n,a;

        cin>>n>>a;

        ll psum=0;

        ll j=1;

        for(int i=0;i<n;i++){

            psum += exp(a, j);

            psum = psum % mod;

            a = (a * exp(a, j)) % mod;

           

            j += 2;

        }

        cout<<psum<<"\n";

        

    }

}

can anyone help me out please i couldnt guess out whats wrong with my code as it is giving wrong answer on submission even though after the correct use of modulo exponentiation ;p

Firstly, Format your code

Secondly, it’s overflow.
Replace

return (r * r * a) % mod;

with

return (((r * r)%mod) * a) % mod;
1 Like

int n=in.nextInt();
long a=in.nextLong();
if(n==0){
System.out.println(0);
break;
}
long p[]=new long[n];
long sum=a;
p[0]=a;long h=1;
for(int i=1;i<n;i++){
a=(long)(a*p[i-1]);
p[i]=(long)Math.pow((a),h+2);
sum=sum+p[i]%1000000007;
h+=2;
}
System.out.println(sum);
Help needed can’t find why it’s not working?

yes there was the mistake thanks for the help :3

u have to use fast exponentiation rather than using predefined .math :: power library function

Thanks I got it!