pacoverflow
pacoverflow

Reputation: 3881

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

I tried the following in a Perl script:

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

It incorrectly outputted 0.

Then I found an answer saying to use bignum:

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

It correctly outputted 9999999999999999.

But bignum just converts all integer constants into a Math::BigInt. So I tried the following which should be the same as using bignum:

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

But that incorrectly outputted 0. Am I doing something wrong with Math::BigInt?

Upvotes: 1

Views: 397

Answers (1)

melpomene
melpomene

Reputation: 85767

You're still using native Perl numbers first and then converting them to Math::BigInt objects. Try this instead:

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

Quoting from 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

(Also, don't use $b outside of sort and similar routines.)

Upvotes: 9

Related Questions