Thanks for the link :-) I also tried the first assignment yesterday, but with a small speed-up included. See for comparison:
#!/usr/bin/perl
use warnings;
use strict;
my %cache = (1 => 0);
sub _three_n_plus_1 {
no warnings qw/recursion/;
my ($n,$count) = @_;
$count ||= 1;
return $count + $cache{$n} if exists $cache{$n};
if($n % 2){
$cache{$n} = _three_n_plus_1(3*$n+1, $count+1) - $count;
return $cache{$n} + $count;
}else{
$cache{$n} = _three_n_plus_1($n/2, $count+1) - $count;
return $cache{$n} + $count;
}
}
sub three_n_plus_1 {
my ($i,$j) = @_;
my $max = 0;
for my $x ($i<$j ? $i..$j : $j..$i){
my $t = _three_n_plus_1($x);
$max = $t if $t > $max;
}
print "$i $j $max\n";
}