If we use Brute force we can simply multiply (
Question is can we optimize it further ?Yes we can.
Before we start remember this basic property
let's first take the value of
let's define
Now let's iterate over the binary of
-
check the
$0th$ bit of$b(13)=110|1|$ is it set or not? yes it's set.
then we need to multiply$a^{2^0}=a^1$ (the value of$x$ is$a\%M$ ).
$result = result * x \% M$ [after this operation the value of$result$ will become$a\%M$ ]
$x=x*x%M$ [after this operation the value of$x$ will become$a^2\%M$ ] -
check the
$1st$ bit of$b(13)=11|0|1$ is it set or not? no it's not.
then we don't need to multiply anything to result.
$x=x*x\%M$ [after this operation the value of$x$ will become$a^4\%M$ ] -
check the
$2nd$ bit of$b(13)=1|1|01$ is it set or not? yes it's set.
so we need to multiply$a^{2^2}=a^4$ (the value of$x$ is$a^4\%M$ ).
$result = result * x \% M$ [after this operation the value of$result$ will become$a * a^4\%M$ ]
$x=x*x\%M$ [after this operation the value of$x$ will become$a^8\%M$ ] -
check the
$3rd$ bit of$b(13)=|1|101$ is it set or not? yes it's set.
so we need to multiply$a^{2^3}=a^8$ (the value of$x$ is$a^8\%M$ ).
$result = result * x \% M$ [after this operation the value of$result$ will become$a * a^4 * a^8\%M$ ]
$x=x*x\%M$ [after this operation the value of$x$ will become$a^{16}\%M$ ]
we iterated over all the bits of
Can you guess the overall complexity? Yes it's
If you see a problem where
const int M = 1000000007;
int mpow(int a, int b) {
int r = 1;
while (b) {
if (b & 1) {
r = (r * a) % M;
}
a = (a * a) % M;
b >>= 1;
}
return r;
}