Created
May 16, 2021 12:31
-
-
Save dogbert17/36ff5b85a46de83930b27184e46d523a to your computer and use it in GitHub Desktop.
Slowdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Longest Collatz sequence - Which starting number, under one million, produces the longest chain? | |
#real 2m18.424s | |
#user 2m17.600s | |
#sys 0m0.056s | |
# This is Rakudo version 2016.06-11-g2c61fda built on MoarVM version 2016.06 | |
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"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment