在Perl中使用大数字

时间:2014-11-19 11:05:01

标签: perl

我有一个场景,我需要2个非常大的二进制字符串(有100个字符),我需要添加它们。

问题是我得到了2.000xxxxxxxxxxe + 2形式的答案,而我需要准确的答案,作为另一个100个字符长的字符串。

chomp($str1=<STDIN>);
chomp($str2=<STDIN>);
print "Str 1 is $str1\n";
print "Str 2 is $str2\n";
$t = $str1 + $str2;
print "Sum is $t\n";

示例输入

1001101111101011011100101100100110111011111011000100111100111110111101011011011100111001100011111010
1001101111101011011100101100100110111011111011000100111100111110111101011011011100111001100011111010

样品输出
Str1是

1001101111101011011100101100100110111011111011000100111100111110111101011011011100111001100011111010      

Str2是

1001101111101011011100101100100110111011111011000100111100111110111101011011011100111001100011111010

总和是

2.0022022220202e+099

2 个答案:

答案 0 :(得分:4)

如前所述,您可以使用Math::BigInt核心模块

use Math::BigInt;

# chomp($str1=<STDIN>);
# chomp($str2=<STDIN>);
# print "Str 1 is $str1\n";
# print "Str 2 is $str2\n";

my $t = Math::BigInt->new("0b$str1") + Math::BigInt->new("0b$str2");

print $t->as_bin;

答案 1 :(得分:0)

为了对字符串执行算术运算,Perl将它们转换为浮点数,即inherently imprecise。如果您想避免这种情况,请使用已建议的Math::BigInt ...或自行推送。

######## WARNING/GUARANTEE: This is practically certain to be
# slower, buggier, less portable, and less secure than Math::BigInt.
# In fact, I planted a security hole just to prove a point.  Enjoy.

use strict;
use warnings;

sub addition {
    my ($int1, $int2) = @_;
    my @int1 = reverse split //, $int1;
    my @int2 = reverse split //, $int2;
    my $len = scalar(@int1>@int2 ? @int1 : @int2);

    my @result;
    my $carry = 0;
    for (my $i=0; $i < $len; ++$i)
    {
        $int1[$i] |= 0;
        $int2[$i] |= 0;
        my $sum = $carry + $int1[$i] + $int2[$i];
        if ($sum >= 10)
        {
            $carry = int($sum / 10);
            $sum %= 10;
        }
        push @result, $sum;
    }
    push @result, $carry if $carry;
    return join ('', reverse @result);
}