http://qs321.pair.com?node_id=801379

perl -le'$;=3;$;=~s/./$&?30:3/eg for 3..pop;print length$;' 12
Replace command-line argument 12 with any positive integer N to get the Nth Fibonacci number. Starts getting pretty slow for me after N=30, by the nature of the algorithm.

Can you see how it works?

blokhead

Replies are listed 'Best First'.
Re: Fibonacci numbers using regexes (threes are wild)
by Anonymous Monk on Nov 29, 2009 at 06:23 UTC

    $; is used as an ordinary variable. It could have been $f. For each character in the string, if zero it is replaced by 3, if 3 it is replaced by 30, thus yielding the sequence 3, 30, 303, 30330, 30330303. Each value is simply the concatenation of the previous two values; for example, 30330303 is 30330 followed by 303. Thus, its length is the sum of the two previous lengths, yielding Fiboncci numbers. If you replace 0's by newborn and 3's by old rabbits you get Fibonacci's model of population growth

Re: Fibonacci numbers using regexes (threes are wild)
by pmonk4ever (Friar) on Dec 01, 2009 at 00:35 UTC
    blokhead,

    I tried to execute this on ActiveState Win32 v5.10.0 and received the following error message:

    Can't find string terminator "'" anywhere before EOF at -e line 1. The filename, directory name, or volume label syntax is incorrect.

    I copied the code exactly as written, there are 2 string terminators in the line of code.

    Any suggestions?

    Thanks

    pmonk4ever

    "No trees were harmed in the creation of this node. However, a rather large number of electrons were somewhat inconvenienced."

      I haven't used windows in about 10 years, but a voice in my head says that windows may not support single quotes for command-line arguments. Try using double quotes instead? In unix systems, double quotes will cause $variables to be interpolated so I used single quotes.

      blokhead

        Thanks, it works now, I keep forgetting about those pesky double quotes.

        30 was pretty fast for me, but 48 is taking a bit of time...

        pmonk4ever

        "No trees were harmed in the creation of this node. However, a rather large number of electrons were somewhat inconvenienced."