
Untitled
By: a guest on
May 8th, 2012 | syntax:
None | size: 0.47 KB | hits: 9 | expires: Never
size_t modpow(size_t x, size_t power, size_t mod)
{
/* Only powers of two need to be multiplied together the get the result.
*
* Here we use the Euclidean algorithm to retreive those powers,
* multiplying them together and reducing by the modulus at each iteration
* to "avoid" overflow (ha!). */
size_t result = 1;
while (power > 0) {
if ((power % 2) == 0) {
result = (result * x) % mod;
}
power /= 2;
x = (x * x) % mod;
}
return result;
}