我目前使用的算法很快就会遇到极高的数字。算法中的一个步骤是将 x 提升到应用于 y 的 totient 函数的结果。结果是您可能会遇到非常大的数字。
例如。计算 10 模 53 的 multiplicative order 时:
10^totient(53) == 10^52 == 1 * 10^52
以下算法在避免大数方面表现更好,但在 10^mOrder 大于数据类型的容量时仍然失败:
mOrder = 1
while 10^mOrder % 53 != 1
if mOrder >= i
mOrder = 0;
break
else
mOrder = mOrder + 1
最佳答案
使用模幂运算,可以计算 (10 ^ mOrder % 53) 或一般情况下的任何 (a ^ b mod c),而不会得到比 c 大得多的值。有关详细信息,请参阅 Wikipedia,也有此示例代码:
Bignum modpow(Bignum base, Bignum exponent, Bignum modulus) {
Bignum result = 1;
while (exponent > 0) {
if ((exponent & 1) == 1) {
// multiply in this bit's contribution while using modulus to keep result small
result = (result * base) % modulus;
}
// move to the next bit of the exponent, square (and mod) the base accordingly
exponent >>= 1;
base = (base * base) % modulus;
}
return result;
}