|
|
| Keep It Simple, Stupid | |
| PerlMonks |
Re: Adding 2 + 2by roboticus (Chancellor) |
| on Jan 30, 2007 at 22:53 UTC ( [id://597495]=note: print w/replies, xml ) | Need Help?? |
This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.
At first, I tried this simple recursive algorithm:
which yields the results:
But I then realized that the algorithm used is essentially tail-recursive. Thus, it can be optimized! Converting the add routine from tail-recursive form to an iterative form yields:
Now all that remained is to verify that the conversion was worthwhile:
Running the benchmarking program shows:
Success! The iterative version is *much* faster than the recursive one. I'm certain that this new algorithm for adding should be used in all future programs, as the iterative version is better both in speed (it's nearly twice as fast!) as well as consuming far less memory than it's recursive counterpart when adding large numbers. --roboticus Awaiting his Turing prize for this valuable discovery...
In Section
Cool Uses for Perl
|
|
||||||||||||||||||||||||