[H-GEN] Which is better?
Mark Suter
suter at zwitterion.humbug.org.au
Thu Apr 29 08:15:21 EDT 2004
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Folks,
andrae> My number one rule when it comes to code is
andrae>
andrae> "Help the reader reason about the code".
Here are two functions to calculate a Fibonacci number[1]. Both
will produce the same correct results; however, there are clearly
differences. I'd use fib1 until it proved a bottleneck.
sub fib1 {
my ($i) = @_;
return 0 if $i == 0;
return 1 if $i == 1;
return recursive($i - 1) + recursive($i - 2);
}
sub fib2 {
sub helper {
if ($_[0] % 2 == 0) {
my @m = helper($_[0] / 2);
return ( $m[0]**2 + $m[1]**2, $m[1] * ($m[0] + $m[2]), $m[1]**2 + $m[2]**2 );
} else {
return (1, 1, 0) if $_[0] == 1;
my @m = helper($_[0] - 1);
return ( $m[0] + $m[1], $m[0], $m[1] );
}
}
return 0 if $_[0] == 0;
return 1 if $_[0] == 1;
return (helper($_[0] - 1))[0];
}
[1] http://en.wikipedia.org/wiki/Fibonacci_number
Yours sincerely,
- -- Mark John Suter | I know that you believe you understand
suter at humbug.org.au | what you think I said, but I am not sure
gpg key id 2C71D63D | you realise that what you heard is not
mobile 0411 262 316 | what I meant. Robert J. McCloskey
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)
Comment: Check Keyservers or http://zwitterion.org/keys/
iD8DBQFAkPHZRYso2ixx1j0RAltcAJ9qPAxWV9Rql2eWZv+GW4uwjOq4UgCcDBbD
v1DholqRC78f2tfVdvWBkfI=
=QOBc
-----END PGP SIGNATURE-----
More information about the General
mailing list