【发布时间】:2021-06-04 02:54:41
【问题描述】:
对于以下 C 和 python 中的两种实现,我得到了不同的答案。 在 Python 中
print(pow(15, 47413144071, 94826288143))
打印 1
但在 C 中
#include<stdio.h>
unsigned long Power(unsigned long A, unsigned long B, unsigned long X)
{
unsigned long res = 1;
while( B > 0 )
{
if( B & 1UL )
{
res = ( res * A ) % X;
}
A = ( A * A ) % X;
B >>= 1UL;
}
return res;
}
int main()
{
printf("%lu", Power(15, 47413144071, 94826288143));
return 0;
}
打印: 893231448 任何帮助表示赞赏。
【问题讨论】:
-
一个
unsigned long只保证能够表示0到4294967295范围内的值(虽然标准允许 表示更大的范围,但它是不需要)。您传递的值B和C都超过了这个值。如果您的实现提供 32 位unsigned long,则传递的值将以4294967296为模减少。 -
我这样做了,但它仍然提供如上所述的输出。输出:893231448
-
47413144071-- 你为什么假设 Python 在这里使用unsigned long?由于您将其标记为C++,因此您可以使用uint64_t类型。 -
也使用了 uint64_t。还是不行。
-
C 没有任意精度的整数。您必须自己实现,或者使用外部库,例如
gmp。
标签: python c performance pow exponentiation