I'm trying to perform Modular Exponentiation for large values (upto 64-bits) and I wrote this function for it:
uint64_t modularExp(uint64_t num, uint64_t exp, uint64_t mod)
{
string expBits = bitset<64>(exp).to_string();
expBits = expBits.substr(expBits.find("1")+1);
string operations = "";
uint64_t result = num;
for (int i = 0; i < expBits.length(); ++i)
{
result = (uint64_t)pow(result, 2) % mod;
if (expBits[i] == '1')
result = (result * num) % mod;
}
return result;
}
This works good with small numbers (8 digits or less) but for large numbers, even though they're in the 64 bit range, the result comes out wrong.
Additionally, when the value of mod exceeds 4294967296 (Max 32 bit value), the result just comes out as zero. I suspect the pow function perhaps has a role to play in this issue but I can't figure it out for sure.
Any advice would be greatly appreciated.