I'm not sure how you add on paper, but for me, I only ever consider one digit of the number at a time. From my perspective, the problem is that your inputs can be arbitrary numbers, not just digits.

To get all elements to be digits, you can:

Here's an example of the last approach:

#!/usr/local/bin/perl use strict; use warnings; use constant BASE => 10; run( @$_ ) for ( [ 'case1 when @a > @b', [qw(1 0 9 15 6)], [qw( 1 1 4 )], ], [ 'case2 when @a < @b', [qw( 1 5 9)], [qw(10 9 3 6)], ], [ 'case3 when @a == @b', [qw(1 1 6 9 2)], [qw(2 1 4 4 8)], ] ); sub run { my ($msg, $a, $b) = @_; local $\ = "\n"; # or use say on 5.10 print "# $msg"; print "@$a"; print "@$b"; print "__________+"; my @result = add( $a, $b ); print "@result"; print ""; } { use integer 'division'; sub add { my ($a, $b) = @_; my @sum; my $carry = 0; while (@$a || @$b || $carry) { my $_a = rem_lsd($a); my $_b = rem_lsd($b); my $sum = $_a + $_b + $carry; $carry = $sum / BASE; $sum %= BASE; unshift @sum, $sum; } return @sum; } # get (remove) least significant digit # corrects for multidigit inputs (by removing the lsd from the las +t element) # returns zero when array is empty sub rem_lsd { my $elem = pop @{$_[0]} || 0; # put back extra digits if (my $extra = $elem / BASE) { push @{$_[0]}, $extra; } $elem %= BASE; return $elem; } }

In reply to Re: Arithmetical Simulation by plobsing
in thread Arithmetical Simulation by biohisham

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.