Hello to all, i try to code the binary exponentiation algorithm but unfortunately it is not working as desire.
I decided to switch back to You could try using std::numeric_limits<int>::digits to determine the values and sizes or using CHAR_BIT.
My logic is define at below.
Look at most significant set bit(1) and discard it which follow by scanning from Left to right
If bit Is 1 then
base * result * result % modulus;
else
result * result % modulus;
My question is how to translate these to code.
Another question is i doubt whether the modulus step need to performed in each loop or outside the loop.
result = result % modulus at outside of loop or inside of loop at every step.
My current code.
Code:
ulong LeftRightExponentiation(ulong& base,
ulong& exponent, const ulong& modulus)
{
ulong result(1);
// Reverse exponent
exponent = (((exponent & 0xaaaaaaaa) >> 1) | ((exponent & 0x55555555) << 1));
exponent = (((exponent & 0xcccccccc) >> 2) | ((exponent & 0x33333333) << 2));
exponent = (((exponent & 0xf0f0f0f0) >> 4) | ((exponent & 0x0f0f0f0f) << 4));
exponent = (((exponent & 0xff00ff00) >> 8) | ((exponent & 0x00ff00ff) << 8));
exponent = ((exponent >> 16) | (exponent << 16));
while (exponent)
{
// Check Least Significant Bit after reverse
if ((exponent & 1) == 1)
{
// Square and Multiply Base
result = base * (result * result);
}
else
{
// Square only
result = result * result ;
}
exponent >>= 1;
}
result = result % modulus;
return result;
}
Thanks for your help.