Skip to content

Instantly share code, notes, and snippets.

@scruss
Last active September 29, 2022 20:28
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 scruss/f7af59d59efd6af2c7964cb8f771c828 to your computer and use it in GitHub Desktop.
Save scruss/f7af59d59efd6af2c7964cb8f771c828 to your computer and use it in GitHub Desktop.
there's something badly wrong with raku ...
#!/usr/bin/env perl
# collatz-memo.pl
# run time: appx 7 s
# output: max: 8400511 steps: 685
use v5.20;
use strict;
use warnings;
my ( $maxsteps, $maxval, $n, $steps, $x ) = qw/0 0 0 0 1/;
my @s;
$s[$x] = 0;
foreach $x ( 1 .. 10000000 ) {
$steps = 0;
$n = $x;
while ( ( $n > 1 ) && ( $n >= $x ) ) {
$n = ( $n & 1 ) ? 3 * $n + 1 : $n >> 1;
$steps++;
}
$steps += $s[$n];
$s[$x] = $steps;
( $maxsteps, $maxval ) = ( $steps, $x ) if ( $steps > $maxsteps );
}
say 'max: ', $maxval, ' steps: ', $maxsteps;
exit;
#!/usr/bin/env raku
# collatz-memo - uses over 10 GB and fails to complete in 5+ minutes
# raku version v2022.07
# equivalent Perl5 completes in 7 s and minimal memory
my ( $maxsteps, $maxval, $n, $steps, $x ) = qw/0 0 0 0 1/;
my @s;
@s[$x] = 0;
# Perl 5 used
# foreach $x ( 1 .. 10000000 ) {
loop ($x=1; $x <= 10000000; $x++) {
$steps = 0;
$n = $x;
while ( ( $n > 1 ) && ( $n >= $x ) ) {
$n = ( $n & 1 ) ?? 3 * $n + 1 !! $n +> 1;
$steps++;
}
$steps += @s[$n];
@s[$x] = $steps;
( $maxsteps, $maxval ) = ( $steps, $x ) if ( $steps > $maxsteps );
}
say 'max: ', $maxval, ' steps: ', $maxsteps;
exit;
@scruss
Copy link
Author

scruss commented Sep 29, 2022

I'm pretty amazed that I managed to pick up the +> thing from Perl to Raku guide - in a nutshell: I think the interpreter complained so I read up on it. It's a shame that Raku doesn't switch from int to bigints automatically like Python does: it's a huge speed increase

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment