Lazy, fast, and I think it's correct.
use strict;
use warnings;
sub lazy_ham {
my ($how_many) = @_;
my @output_stream = (1);
my @streams = map {
my $base = $_; # All your base are belong to us
my $index = 0;
sub {
if (@_) {
return $base * $output_stream[$index];
} else {
return $base * $output_stream[$index++];
}
}
} (2, 3, 5);
for (1..$how_many) {
# Find the lowest next item in the available streams
my ($lowest) = sort {$a <=> $b} map {$_->('peek')} @streams;
$_->('peek') == $lowest and $_->() for @streams;
push(@output_stream, $lowest);
}
shift @output_stream; # Get rid of the seed 1
@output_stream;
}
print join(', ', lazy_ham(1000)), "\n";
2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, 36, 4
+0, 45, 48, 50, 54, 60, 64, 72, 75, 80, 81, 90, 96, 100, 108, 120, 125
+, 128, 135, 144, 150, 160, 162, 180, 192, 200, 216, 225, 240, 243, 25
+0, 256, 270, 288, 300, 320, 324, 360, 375, 384, 400, 405, 432, 450, 4
+80, 486, 500, 512, 540, 576, 600, 625, 640, 648, 675, 720, 729, 750,
+768, 800, 810, 864, 900, 960, 972, 1000, 1024, 1080, 1125, 1152, 1200
+, 1215, 1250, 1280, 1296, 1350, 1440, 1458, 1500, 1536, 1600, 1620, 1
+728, 1800, 1875,...
Caution: Contents may have been coded under pressure.