【发布时间】:2020-01-09 13:51:10
【问题描述】:
我尝试了两个函数用于大基数的模幂运算返回错误结果, 其中一个功能是:
uint64_t modular_exponentiation(uint64_t x, uint64_t y, uint64_t p)
{
uint64_t res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0)
{
// If y is odd, multiply x with result
if (y & 1)
res = (res*x) % p;
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % p;
}
return res;
}
对于输入x = 1103362698 ,y = 137911680 , p=1217409241131113809;
它返回值(x^y mod p):749298230523009574(不正确)。
正确的值为:152166603192600961
我尝试的另一个函数给出了相同的结果,这些函数有什么问题? 另一个是:
long int exponentMod(long int A, long int B, long int C)
{
// Base cases
if (A == 0)
return 0;
if (B == 0)
return 1;
// If B is even
long int y;
if (B % 2 == 0) {
y = exponentMod(A, B / 2, C);
y = (y * y) % C;
}
// If B is odd
else {
y = A % C;
y = (y * exponentMod(A, B - 1, C) % C) % C;
}
return (long int)((y + C) % C);
}
【问题讨论】:
-
如果
x= 1103362698、y= 137911680 和p=137911680 那么 152166603192600961 不可能是正确的值,因为它大于 @9876543。3当我使用这些参数运行此函数时,我得到了 136204416。 -
根据dcode.fr/modular-exponentiation,这是正确答案。
-
抱歉 p=152166603192600961,我已经编辑了我的问题
标签: c modular-arithmetic mod exp