You can make it even faster by using bitwise operators to check for parity (n&1 instead of n%2==1) and to divide by two (n=n>>1 instead of n=n/2).
This is truly a great psot thanks for sharing. Excellent and decent post. I found this much informative, as to what I was exactly searching for. Thanks for such post and please keep it up.
https://www.youtube.com/watch?v=wAyrtLAeWvI&list=PL2_aWCzGMAwLz3g66WrxFGSXvSsvyfzCO&index=7 great explanation by mycodeschoolâŚ
can somebody explain this solution
@kuruma
One thing I would like to add ⌠your code fails when the exp = 0 , Output should be 1 but your code doesnât produce any output . Adding and if statement will do the job .
in the wikipedia solution canât we directly return base1%1000000007
Hey, I donât clearly understand the implementation. As per the formula above for the fast-exponentiation method given on wikipedia, why donât we write itâs implementation as given below.
long long fast_exp_1(long long x, int n)
{
if(n==1)
return x;
if(!(n&1))
return fast_exp_1(pow(x,2),n/2) % MOD;
else
return (x*fast_exp_1(pow(x,2),(n-1)/2)) % MOD;
}
Your help is really appreciated. Thanks in advance
pow function is costly. It can potentially increase runtime by a factor of at least 5. I got TLE on using pow(2,x)
when T.L. was 2 seconds, but replacing it with 1<<x
got AC in 0.2 secs.