Skip to content

Instantly share code, notes, and snippets.

@dogbert17
Created October 3, 2016 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dogbert17/6cdf82145f61495936eeb6c64a2d58a7 to your computer and use it in GitHub Desktop.
Save dogbert17/6cdf82145f61495936eeb6c64a2d58a7 to your computer and use it in GitHub Desktop.
# perl6, 130 secs on my machine
use v6;
my $maxChainLen = 0;
my $maxChainLenNum = 0;
my @cache is default(0);
for (1..1_000_000) -> $x {
my $num = $x;
my $chainLen = 0;
while $num > 1 {
if $num < 75_000 && (@cache[$num] != 0) {
$chainLen += @cache[$num];
last;
}
$chainLen++;
$num = ($num % 2 == 0) ?? $num div 2 !! 3 * $num + 1;
}
$chainLen++ if $num == 1;
@cache[$x] = $chainLen if $x < 75_000;
if $chainLen > $maxChainLen {
$maxChainLen = $chainLen;
$maxChainLenNum = $x;
}
}
say "Max chain length was $maxChainLen for number $maxChainLenNum";
# perl5 , seven seconds
use strict;
my $maxChainLen = 0;
my $maxChainLenNum = 0;
my @cache = ();
for (my $x = 1; $x <= 1_000_000; $x++) {
my $num = $x;
my $chainLen = 0;
while ($num > 1) {
if ($num < 75_000 && defined($cache[$num])) {
$chainLen += $cache[$num];
last;
}
$chainLen++;
$num = ($num % 2 == 0)? $num / 2: 3 * $num + 1;
}
$chainLen++ if $num == 1;
$cache[$x] = $chainLen if ($x < 75_000);
if ($chainLen > $maxChainLen) {
$maxChainLen = $chainLen;
$maxChainLenNum = $x;
}
}
print "Max chain length was $maxChainLen for number $maxChainLenNum";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment