Last active
June 30, 2021 22:38
-
-
Save rassoc/7cc2d9b853fd2164dbdd0b98e9da3ab9 to your computer and use it in GitHub Desktop.
collatz
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
# 0.53 s, 31424 kb | |
$memo = {} | |
def collatz(n) | |
return $memo[n] if $memo[n] | |
$memo[n] = case | |
when n == 1 then 1 | |
when n.even? then 1 + collatz(n.div 2) | |
else 1 + collatz(3 * n + 1) | |
end | |
end | |
(1..100_000).each { |n| puts "#{n} #{collatz n}" } |
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
# 21.89 s, 197740 kb | |
use experimental :cached; | |
sub Collatz ($n) is cached { | |
given ($n) { | |
when (1) { 1 }; | |
when ($n %% 2 ) { 1 + Collatz($n / 2) }; | |
when ($n !%% 2 ) { 1 + Collatz(3 * $n + 1) }; | |
} | |
} | |
(1 .. 1E5).map: -> $n { | |
say join ' ', $n, Collatz $n; | |
} |
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
# 4.40 s, 157024 kb | |
sub collatz ($n) { | |
state %memo; | |
return %memo{$n} if %memo{$n}:exists; | |
%memo{$n} = do given $n { | |
when 1 { 1 }; | |
when $n %% 2 { 1 + collatz($n div 2) }; | |
default { 1 + collatz(3 * $n + 1) }; | |
} | |
} | |
say $_, ' ', collatz $_ for 1..100_000; |
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
# 12.00 s, 175020 kb | |
use experimental :cached; | |
sub collatz ($n) is cached { | |
given $n { | |
when 1 { 1 }; | |
when $n %% 2 { 1 + collatz($n div 2) }; | |
default { 1 + collatz(3 * $n + 1) }; | |
} | |
} | |
say $_, ' ', collatz $_ for 1..100_000; |
japhb
commented
Jun 30, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment