Is there a better solution than this :
2^n mod(m)
{
if n=0
return 1;
r=2^(n-1)mod(m);
if 2r < m
return 2r;
if 2r > =m
return 2r-m;
}
Is there a better solution than this :
2^n mod(m)
{
if n=0
return 1;
r=2^(n-1)mod(m);
if 2r < m
return 2r;
if 2r > =m
return 2r-m;
}
This can be sped up a bit. Instead of iterating over exponents, a process called repeated squaring is used. You iteratively square and reduce mod m to obtain $a^k$ where $k$ is a power of $2$. Then you multiple together the factors you need until the exponent is correct. Remember, the base 2 expansion of the exponent tells you which factors you need.