use strict; use warnings; use List::Util qw( sum ); sub calcIt { our $r; local $r = sub { my ($depth) = @_; if ($depth == 0) { return sum 1..$_; } else { return sum map { $r->($depth-1) } 1..$_; } }; return $r->(5) for $_[0]; } print(calcIt(10), "\n"); # 11440 print(calcIt(20), "\n"); # 657800 #### use strict; use warnings; use List::Util qw( sum ); { my %memoize; sub calcIt { our $r; local $r = sub { my ($depth) = @_; return $memoize{"$depth:$_"} ||= ( ($depth ? sum map { $r->($depth-1) } 1..$_ : $_ * ( $_ + 1 ) / 2 ) ); }; return $r->(5) for $_[0]; } } print(calcIt(10), "\n"); # 11440 print(calcIt(20), "\n"); # 657800