If you understand the growth pattern properly, you will realize that A(4,3) is not running with the naive algorithm in your lifetime on a computer, and even if it did, Perl would be unable to represent the answer.
Try A(3,6), A(3,7) and A(3,8) to get an idea of relative performance.
Now if you really want a speed boost, what you want to do isn't make the recursion faster, but rather insert more and more special cases to avoid spending all of the time recursing at the tail. The following executes acceptably:
sub A {
BARE_BLOCK: {
if (0 == $_[0]) {
return 1 + $_[1];
}
elsif (1 == $_[0]) {
return 2 + $_[1];
}
elsif (2 == $_[0]) {
return 3 + 2*$_[1];
}
@_=($_[0] - 1, $_[1] ? A($_[0], $_[1]-1) : 1);
redo BARE_BLOCK;
}
}
And here we find out why to use recursion even if Perl is bad at it. This intelligent optimization would be very hard to write if you first did the low-level optimization of avoiding any recursive calls. Intelligent algorithms beat faster execution of bad ones any time!
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.