#!/usr/bin/perl -w use strict; use warnings; my $ABOUT = "This program adds two positive integers of any size and displays the result.\n" . "Usage: ADD \n\n" . "Example: ADD 19333045834565223108349833745893453 12982372388169001\n\n" . "This program requires two numbers as parameters.\n" . "The parameters may only contain digits (0-9).\n\n"; @ARGV == 2 or die $ABOUT; if (Is_Not_A_Number($ARGV[0]) || Is_Not_A_Number($ARGV[1])) { die $ABOUT; } print ADD($ARGV[0], $ARGV[1]); exit; #################################### sub ADD { my $A = defined $_[0] ? $_[0] : ''; my $B = defined $_[1] ? $_[1] : ''; my $AL = length($A); my $BL = length($B); my $i = ($AL > $BL) ? $AL : $BL; my $CARRY = 0; my $SUM = '0'; my $X; while ($i-- > 0) { $X = $AL ? vec($A, --$AL, 8) : 48; $X += ($BL ? vec($B, --$BL, 8) : 48) + $CARRY; $CARRY = $X > 105 ? 1 : 0; vec($SUM, $i, 8) = $X - ($CARRY ? 58 : 48); } return ($CARRY ? '1' : '') . $SUM; } #################################### sub Is_Not_A_Number { @_ or return 1; my $N = shift; return 1 unless defined $N; my $L = length($N); return 1 unless $L; my $C; while ($L-- > 0) { $C = vec($N, $L, 8); return 1 if ($C < 48 || $C > 57); } return 0; }