#!/usr/bin/perl
# Description: Add arbitrary-length integers
#
# Motivation for this simple script came as bug
# with expr(1) was uncovered in some operating systems,
# where simple mathematics failed for large integers
#
# z=$(expr 28880458 \* 90 / 100)
#
# So, the question was: how to add two very large integers...
# and the answer: convert the integers into array of single
# digits and perform addition starting from Least Significant Digit
# by saving the result and carry to the next Digits...
#
# Last Update: 4 June 2014
# Designed by: Dusan U. Baljevic (dusan.baljevic@ieee.org)
# Coded by: Dusan U. Baljevic (dusan.baljevic@ieee.org)
#
# Copyright 2006-2015 Dusan Baljevic
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see .
# Two integers to add
#
my $FirstInt = "23493802876875704377397806786672945850550505050505";
my $SecInt = "20938512689456505679373769765782960171653949850908973838387";
# Convert integers into arrays
#
my @A = split('', $FirstInt);
my @B = split('', $SecInt);
my $carry = q{};
my @FINARR = ();
my $BASE = 10;
print "TASK: Add large integers of arbitrary lengths\n";
print "First integer $FirstInt\n";
print "Second integer $SecInt\n";
# Reverse the arrays to start the additions from Least Significant Digits
#
@B = reverse @B;
@A = reverse @A;
sub calc {
$resA = shift @A;
$resB = shift @B;
$calc = $resA + $resB + $carry;
if ( $calc >= $BASE ) {
$carry = int($calc / 10);
$calc = $calc % $BASE;
}
else {
$carry = 0;
}
push(@FINARR, $calc);
}
if ( length(@A) > length(@B) ) {
# Decimal number in array @A has longer number of digits\n";
#
while ( @A ) {
calc();
}
}
else {
# Decimal number in array @B has longer number of digits\n";
#
while ( @B ) {
calc();
}
}
print "\nRESULT ",join('', reverse(@FINARR)), "\n";
exit(0);