2009/7/10 Telemachus <telemac...@arpinum.org>: > On Fri Jul 10 2009 @ 9:26, Dermot wrote: >> The algorithm works perfectly but my understanding of it's workings is amiss. >> >> When I look at this I see $E initialised and then concatenate with the >> the modulus of > > It helps for me to walk through it visually, indenting once each time the > script needs to call the binary sub-routine. Notice that it keeps going down > and inward, until it "bottoms out" on the base case. At that point, the > answers > ripple back up to fit into the calls to binary($E) that were left hanging > (because in those cases $E wasn't 1 or 0). Maybe this will help you as well. > > > Does 37 == 0 || 1? No; continue... > $k = 18; $b = 1; $E = binary(18) -> go do that... > Does 18 == 0 || 1? No; continue... > $k = 9; $b = 0; $E = binary(9) -> go do that... > Does 9 == 0 || 1? No; continue... > $k = 4; $b = 1; $E = binary(4) -> go do that... > Does 4 == 0 || 1? No; continue... > $k = 2; $b = 0; $E = binary(2) -> go do that... > Does 2 == 0 || 1? No; continue... > $k = 1; $b = 0; $E = binary(1) -> go do that... > Does 1 == 0 || 1? Yes; return 1 > $E = 1; return 1 . 0 > $E = 10; return 10 . 0 > $E = 100; return 100 . 1 > $E = 1001; return 1001 . 0 > $E = 10010; return 10010 . 1 >
Yes this does help. It makes a lot more sense when I get to view the whole execution visually like this. So the final return statement (as Shawn pointed out) isn't used until $n is either 0 or 1. In effect the whole thing loops from: my ($n) = @_; return return $n if $n == 0 || $n == 1; my $k = int($n/2); my $b = $n % 2; my $E = binary($k); Then un-winds itself, returning in reverse order. I want to thank you both for the time and energy you've put in. There's been a lot of typing there and it's much appreciated. Dp. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/