EDIT: It seems that most web sites (and my math text) do agree that the sequence starts 1 1, not 0 1.

The function could be more simply (and correctly, since the function specified didn't give the right values) written as:

sub fibonacci { return 1 if $_[0] < 3; fibonacci($_[0]-1) + fibonacci($_[0]-2); }
Or even:
sub fibonacci { $_[0] < 3 ? 1 : fibonacci($_[0]-1) + fibonacci($_[0]-2); }
Where the number returned is the nth number in the fibonacci sequence, n being the number passed to the function:

1 1 2 3 5 8 13 etc.

Let's say you call the function with 4:

(4) Is 4 < 3? No. Return (4-1) + (4-2).
(4-1) Is 3 < 3? No. Return (3-1) + (3-2).
(3-1) Is 2 < 3? Yes. Returning 1.
(3-2) is 1 < 3? Yes. Returning 1.
(4-1) Returning 1 + 1.
(4-2) Is 2 < 3? Yes. Returning 1.
(4) Returning 2 + 1.
Answer returned is 3, which is the 4th number in the sequence.

See, every number in the sequence is built off the previous two values, each of which is built off the two values previous to it, and so on - all the way back to the first and second values (1 and 2 are < 3), which are 1. If the value passed to the function is 1 or 2, it knows to return 1; otherwise it calls itself twice to determine the previous two numbers in the sequence.


In reply to Re: Puzzled by Recursion. by TedPride
in thread Puzzled by Recursion. by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.