in reply to Question on Recursion
should be&spl($total) if ($len != 1);
$total = &spl($total) if ($len != 1);
Now, what we have here what is called tail-end recursion. The recursion is the last thing in the function. That means you can use a loop instead.
sub spl { my ($num1) = @_; while (1) { my $total = 0; $total = $total + $_ for (split '', $num1); my $len = length ($total); if ($len == 1) { return $total; } $num1 = $total; } }
After some cleaning up, we get:
sub spl { my ($n) = @_; while (length($n) > 1) { my $total = 0; $total = $total + $_ for split '', $n; $n = $total; } return $n; }
or even
use List::Util qw( sum ); sub spl { my ($n) = @_; while (length($n) > 1) { $n = sum split '', $n; } return $n; }
Update: Added last snippet.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Question on Recursion
by AnomalousMonk (Archbishop) on Jan 09, 2009 at 19:23 UTC |