Some test cases wrong

as a is very large b is also very large
hence a^b is very very large so you have to take mod at each step
otherwise data overflow
and after that no use of taking mod

use this code

i hope this helps
if yes hit a like and don’t forgot to mark doubt as resolved :grinning:
if you have more doubts regarding this feel free to ask

this question is before the topic of recursion so i will come back to this quesion later
is it right

No!
There is no need to do it after recusion (yes we can also do it by recursion)
But one can use while loop to calculate the modular exponentiation , I have done that!!

if you want to do it iterative
yes you can obviously do that
using this

#include<bits/stdc++.h>
using namespace std;
#define int long long int
int ModularExponentiationIter(int a,int b,int c){
	a=a%c;
	int ans=1;
	for(int i=1;i<=b;i++){
		ans=(ans*a)%c;
	}
	return ans;
}
int32_t main(){
	// freopen("input.txt","r",stdin);
	int a,b,c;
	cin>>a>>b>>c;
	cout<<ModularExponentiationIter(a,b,c);
	return 0;
}

but the recursive one is more optimised

i hope this helps
if yes hit a like and don’t forgot to mark doubt as resolved :grinning:
if you have more doubts regarding this feel free to ask

I was not talking of this variant, it is O(n)
But following is O(logn)

int power( int x, unsigned int y, int p)

{

int res = 1; // Initialize result

x = x % p; // Update x if it is more than or

// equal to p

if (x == 0) return 0; // In case x is divisible by p;

while (y > 0)

{

// If y is odd, multiply x with result

if (y & 1)

res = (res*x) % p;

// y must be even now

y = y>>1; // y = y/2

x = (x*x) % p;

}

return res;

}

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.