in reply to Arithmetical Simulation
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:
#!/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; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Arithmetical Simulation
by biohisham (Priest) on Jul 31, 2009 at 14:11 UTC |