Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Question on Recursion

by ikegami (Patriarch)
on Jan 09, 2009 at 11:06 UTC ( [id://735152]=note: print w/replies, xml ) Need Help??


in reply to Question on Recursion

You're ignoring the result of the recursive call.
&spl($total) if ($len != 1);
should be
$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
    FWIW: Yet another snippet, slightly different approach:
    >perl -wMstrict -le "sub T { my $n = 0; $n += $_ for @_; return $n <= 9 ? $n : T(split '', $n); } printf qq{%5s -> %d \n}, $_, T($_) for @ARGV " 1818 1819 1918 1500 5001 51 2300 0230 32 1 9 0 00 00000 10000 00001 1818 -> 9 1819 -> 1 1918 -> 1 1500 -> 6 5001 -> 6 51 -> 6 2300 -> 5 0230 -> 5 32 -> 5 1 -> 1 9 -> 9 0 -> 0 00 -> 0 00000 -> 0 10000 -> 1 00001 -> 1

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://735152]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2024-04-25 13:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found