为什么 Perl 模运算符使用 bignum 而不是 Math::BigInt 来处理大整数?

Why does Perl modulo operator work with large integers using bignum but not Math::BigInt?

我在 Perl 脚本中尝试了以下操作:

$b = 19999999999999999 % 10000000000000000;
print "$b\n";

输出错误0

然后我发现an answer说使用bignum:

use bignum;
$b = 19999999999999999 % 10000000000000000;
print "$b\n";

正确输出了9999999999999999.

但是bignum只是将所有整数常量转换为Math::BigInt。所以我尝试了以下应该与使用 bignum:

相同的方法
use Math::BigInt;
$b = Math::BigInt->new(19999999999999999) % Math::BigInt->new(10000000000000000);
print "$b\n";

但是输出错误0。 Math::BigInt 我是不是做错了什么?

您仍然首先使用本机 Perl 数字,然后将它们转换为 Math::BigInt 对象。试试这个:

my $x = Math::BigInt->new('19999999999999999') % Math::BigInt->new('10000000000000000');

引用自perldoc Math::BigInt

Input given as scalar numbers might lose precision. Quote your input to ensure that no digits are lost:

$x = Math::BigInt->new( 56789012345678901234 );   # bad
$x = Math::BigInt->new('56789012345678901234');   # good

(此外,不要在 sort 和类似例程之外使用 $b。)