#!/usr/bin/perl -w use strict; die "Too little money or you are too greedy!\n" if $ARGV[1] > $ARGV[0]; my $cash = $ARGV[0]; my $amount = $ARGV[1]; my @dispersal; # fill the envelopes while ( $cash > 0 ) { # what would be the next amount in geometric progression my $current = 2**($#dispersal + 1); # if our next number is more than the cash in hand, we'll stuff the last # envelope with the remainder if ( $current > $cash ) { push @dispersal, $cash } # otherwise, take the progression and stuff that else { push @dispersal, $current } # deduct the cash in this envelope $cash -= $dispersal[$#dispersal]; } # perform a numeric sort versus ASCII my @envelope = sort { $a <=> $b } @dispersal; print $#envelope+1 . " are as few envelopes as I can use.\n"; for ( my $i = $#envelope + 1; $i >= 0; $i-- ) { if ( $envelope[$i-1] <= $amount ) { $amount -= $envelope[$i-1]; print "Envelope $i (\$$envelope[$i-1])\n\$$amount remaining\n"; } }