Fibonacci Series in One Line of Perl

Not ground breaking but here are the first 20 terms in the Fibonacci Series.

Code
perl -e'@p=(0,1);until($#p>20){print"$p[-2]\n";push @p,$p[-2]+$p[-1]}'
Output

0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181

Can you do better? What about different languages?

Update: it has been suggested that for languages such as Java and C to be included in this experiment, that only the total number of pure source characters be included in the count. Therefore my perl solution in the comments below has 56 pure source characters.

For more information on the Fibonacci Series see http://en.wikipedia.org/wiki/Fibonacci_number

-3Monkeys

Popularity: 69% [?]

  • DZone
  • StumbleUpon
  • Technorati
  • del.icio.us
  • Slashdot
  • Digg
  • Reddit
  • NewsVine
  • SphereIt
  • e-mail
  • Facebook
  • Google Bookmarks
  • Live
  • Propeller
1 Star2 Stars3 Stars4 Stars5 Stars6 Stars7 Stars8 Stars9 Stars10 Stars (7 votes, average: 5.86 out of 10)
Loading ... Loading ...

66 Responses to “Fibonacci Series in One Line of Perl”

  1. Christopher Finke Says:

    Here it is in PHP:

    echo fibonacci_terms(20);

    Writing fibonacci_terms is left as an exercise for the reader. :-)

  2. 3Monkeys Says:

    I was thinking about this on the drive home and remembered that I had used an array construct to avoid a count comparison. I thought to myself, “I could kill a few characters out of that by using for instead of until, and using a alpha range opposed to a numeric range. My improvement below reduce the total characters to 65 from 70.

    perl -e’@p=(0,1);for(A..T){print”$p[-2]\n”;push@p,$p[-2]+$p[-1]}’

  3. rick Says:

    Yes, but which compiles down to the fewest bytes of machine code? (no i didn’t actually try to assemble this, but it seems about right to me)

    section .data
    string: db “%i\n”,0

    section .code

    start:
    xor edx, edx
    .loop:
    call fibo
    push eax
    push string
    call printf
    add esp, byte 4
    inc edx
    cmp edx, 20
    jl .loop
    xor eax, eax
    retn

    fibo:
    cmp edx, 1
    jle .zeroone

    dec edx
    call fibo
    push eax
    dec edx
    call fibo
    add [esp], eax
    add edx, byte 2
    pop eax
    retn

    .zeroone
    mov eax, edx
    retn

  4. Daniel Spiewak Says:

    ruby -e ‘p,c=0,1;20.times{p p;c=p+p=c}’

    30 characters of pure source. :-) This works too:

    p=0;c=1;20.times{p p;c=p+p=c}

    …and is the same number of characters, but the top one is harder to read, so it must be better. :-)

    And just to show how uselessly verbose some languages are, here’s one in Java (105 chars):

    class T{public static void main(String[] a){int p=0;c=1;while(p<4181){System.out.println(p);c=p+(p=c);}}

  5. bloid Says:

    Got it to this in Groovy:

    i=[0,1];(2..19).each{i<<i[it-2]+i[it-1]};i

  6. Carl Says:

    1st attempt, 52 bytes :

    perl -e ‘$p=0;$l=1;($l,$p)=($p,$l+$p),print$l.”\n”while$l

  7. Carl Says:

    I’ll try again, with slightly better code! 52 bytes :

    $p=0;$l=1;($l,$p)=($p,$l+$p),print”$l\n”while$l<4181

    and 51, if you allow multiple line entries :

    $p=0;$l=1;($l,$p)=($p,$l+$p),print”$l
    “while$l<4181

  8. John Montgomery Says:

    p,n,i=0,1,0
    while i

  9. Mike G. Says:

    2 characters better than the previous perl version (and it doesn’t print that wrong leading 0):
    perl -e’@p=(1,1);map@p=(@p,$p[-1]+$p[-2]),A..T;$,=”\n”;print@p’

    This would be MUCH shorter in APL. Now if only I remembered my APL…

  10. sam Says:

    Here’s a ruby one-liner to get the first n numbers of the Fibonacci sequence:

    def fib(n)n==1?[0]: n==2?[0,1]:(p=fib(n-1);p<<p[-2]+p[-1])end

    so puts fib(20) would give you what you want :)

  11. Huff Monster Says:

    A fib battle huh? Let’s get the Haskell on here:
    fib = 1 : 1 : zipWith (+) fib (tail fib)

    That’s for an infinite list of fib.

    to get the first 20 from that list:
    take 20 fib

  12. Fibonacci en una linea | Masio IT Says:

    [...] leo en 3monkeyweb una especie de reto en donde con una linea de perl se escriben los primeros 20 numeros de la serie [...]

  13. Masiosare Says:

    Javascript, 52 chars

    p=1;for(k=0;k

  14. Mikhail Sayapin Says:

    I don’t think it’s worth competing what language will produce worse complicated tiny code.
    Just tell me what is 100000th Fibonacci number.
    When you’ll get old waiting for this:
    p=0;c=1;100000.times{p p;c=p+p=c}

    Just use good implementation (e.g. in Python):

    from math import log
    def fibonacci_number(num):
    if num > 1, a + ((b * c)

  15. Mikhail Sayapin Says:

    Awful! It ate my code… How can you talk about programming while having broken blog script?

    I don’t think it’s worth competing what language will produce worse complicated tiny code.
    Just tell me what is 100000th Fibonacci number.
    When you’ll get old waiting for this:
    p=0;c=1;100000.times{p p;c=p+p=c}

    Just use good implementation (e.g. in Python):

    from math import log
    def fibonacci_number(num):
    __if num < 2: return num
    __num -= 1
    __b, c, d, e = 1, 0, 0, 1
    __for i in range(int(log(num)/log(2))):
    ____if num & 1:
    ______x = d * b
    ______d, e = x + d * c + e * b, x + e * c
    ____a = b * b
    ____num, b, c = num >> 1, a + ((b * c) << 1), a + c * c
    __f = b + c
    __return d * (b + f) + e * f
    print fibonacci_number(10000)

    And keep away from dangerous 1-line “smart” code. :)

    Anyway, Ruby code is fun, respect Daniel! :)

  16. Jorge Says:

    >> Writing fibonacci_terms is left as an exercise for the reader.

    :-) That’s how I passed my Lisp exam 15 years ago… :-D

  17. analyst Says:

    In python (either in a file or interpretted [2 lines]):
    x,y=0,1;
    while y < 16000: print x; x,y=y,x+y

    looks like 42 to me …

  18. 3Monkeys Says:

    @Mike G. 0 *is* the first term in the sequence, see the Wikipedia article from the post.

  19. Daniel Spiewak Says:

    @3Monkeys

    See! I’m not the only one who has math books saying 1,1,2,3,… :-)

  20. Masiosare Says:


    http://www.masio.com.mx/2007/07/13/fibonacci-en-una-linea/es/

    3Monkeys: I had to edit this post to get the JavaScript to appear.
    Solutions in 53 and 52 characters

    k=0;p=1;while(k<4182){document.write(k);t=p;p+=k;k=t}

    p=1;for(k=0;k<4182;){document.write(k);t=p;p+=k;k=t}

  21. John Montgomery Says:

    Ok, ate my code too (guess it didn’t like the less than sign?):

    p,n=0,1
    for i in range(20):print p;p,n=n,n+p

    So different version – 44 chars of Python (the previous was 50)

  22. John Montgomery Says:

    ack – didn’t see analyst’s version…

  23. Urquan Says:

    In one-line of a-lot of shell scripting languages, it can be done in 71 chars…

    echo “0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181″

    This would be the shortest “algorithm” if the challenge was to print the first 5 terms…

  24. b_jonas Says:

    I can do 25 characters from an earlier fibonacci golf I did.

    dc -e1d[prdk+KdZ5\>x]dsxx

    See http://www.perlmonks.com/?node_id=626425 for the discussion thread.

  25. b_jonas Says:

    Oh, you have to start with zero? I looked only at the command at the perlmonks discussion thread which starts from one, and assumed that it’s correct. Adapting my solution is an exercise to the reader (I think it will cost one more character).

  26. b_jonas Says:

    I can’t seem to do it easily with just one extra character in a hurry, only two, but I’m too lazy to experiment more, sorry.

  27. Ted Streete Says:

    28 source characters in forth (could be 26 if I made the name a single character)

    : fib 1 0 20 0 ?DO dup . dup rot + LOOP ;

  28. Carl Says:

    Perl, 41B :
    perl -l12e ‘$_=1;($_,$?)=($?,$_+$?),print while$_<4e3′

  29. Jim Says:

    Believe it or not, Fortran 77 is fairly respectable on this. 41 characters, counting one byte for each end of line image

    i=0
    j=1
    do1n=1,20
    print*,i
    k=i+j
    i=j
    1j=k

  30. 3Monkeys Says:

    @Jim, I’m impressed by the terseness of the Fortran solution. No way COBOL could do that :)

  31. Beth Tibbitts Says:

    I’m very rusty on my APL but:
    APL:
    +\iota 20

    where “iota” is really one character, the “iota” character

  32. Beth Tibbitts Says:

    OK, i got my APL wrong… apologies. that’s the cumulative sum, not fibonacci…

  33. Why people dislike Perl? | Fabio Kung Says:

    [...] OMG: Fibonacci series in one line of perl. [...]

  34. Vidul Says:

    http://www.vidul.com/articles/2007/07/19/fibonacci-formula

    #!/usr/bin/env ruby #21 chars
    x=1;loop{p$.+=x=$.-x}

    #!/usr/bin/env perl #27 chars
    print$}+=$.=$}-$.||1while.1

  35. Angelbob’s Musings on Programming » Two Mixed Blessings: “How Small Can You Write It?” and “Not Invented Here” Says:

    [...] probably seen various folks talking about how fewer lines of code are better. Every language partisan wants to prove that their language is more expressive than [...]

  36. Brian Szymanski Says:

    I thought the contest was for 1,1,2,3…and whipped up this:
    perl -e ‘$a=1;$a+=$b,print$b=$a-$b,$/for(A..T)’
    which at 38 chars I think is a winner in the perl, starting at F(1)=1 category…

    unfortunately adapting it to 0,1,1… bumps it up 11 characters to 49 chars:
    perl -e ‘print 0,$/;$a=1;$a+=$b,print$b=$a-$b,$/for(A..T)’

    Of course I just now see that there is a perlmonks thread about this which probably kicks my tail…

  37. C Williams Says:

    print reduce (lambda x,y: (x[1],x[0]+x[1], x[2]+[x[1]]), xrange(10), (0,1,[]))[2]

    python 1 liner… 74 chars

  38. Why people dislike Perl? « Fabio Kung Says:

    [...] OMG: Fibonacci series in one line of perl. [...]

  39. Mark Aufflick Says:

    I just blogged the following:

    perl -le ‘print$2while s/(\d*):?(\d*)/($1+$2||1).”:$1″/e’ |head -10

    Notice that it contains no explicit assignment operations nor any explicit initialisation. It also (unlike some of the others above, notably the 27 character implementation) contains both of the leading 1s in the sequence.

    http://mark.aufflick.com/blog/2008/10/05/fibonacci-perl-golf

  40. Mark Aufflick Says:

    Relaxing my no-explicit asssignment rule, I can get the solution down to 37 characters. It’s tough to fit into a one-liner though–since both quotes are used, shell escaping would be required:

    $_=”$’:”.($’+$`||1),print$`while x./:/

  41. maddox_laurence Says:

    I think 0 is technically the 0th term…at least, that’s how I’ve always had to implement the sequence. Anyways…Java:

    class Fibonacci20{
    static{
    for(int a=0,b=1,c=20;–c>0;b=a+(a=b))
    System.out.println(b);
    }
    }

  42. Moduly Led Says:

    Very good news – thanks!

  43. Steve Says:

    Such an excellent text! I have no clue how you were able to say this post..it’d take me days. Well worth it though, I’d suspect. Have you considered selling banners on your website?

  44. Dexter Kamps Says:

    There is evidently a great deal to identify about this. I consider you made some fantastic points in functions also.

  45. tips para bajar de peso Says:

    Top-notch information it is without doubt. My girlfriend has been awaiting for this tips.

  46. zsnare.com,social network,insurance network,health,computer,internet Says:

    zsnare.com,social network,insurance network,health,computer,internet…

    [...]3monkeys » Fibonacci Series in One Line of Perl[...]…

  47. mobile web design Says:

    I not to mention my pals came looking at the great tips and hints located on your web page and then instantly got a terrible suspicion I never expressed respect to the web site owner for those tips. All of the ladies were definitely certainly glad to read them and have in effect in actuality been taking pleasure in them. Appreciate your turning out to be very considerate as well as for opting for this sort of wonderful resources most people are really desirous to discover. Our sincere apologies for not expressing appreciation to you earlier.

  48. mobile website design Glasgow Says:

    We are a group of volunteers and opening a new scheme in our community. Your web site offered us with valuable info to work on. You have done an impressive job and our whole community will be thankful to you.

  49. Voncile Swatek Says:

    I got what you mean , regards for posting .Woh I am glad to find this website through google.

  50. Great New Web Design Blog Says:

    Great New Web Design Blog…

    [...]3monkeys » Fibonacci Series in One Line of Perl[...]…

  51. Yvette Courts Says:

    hello there and thanks for your information – I have certainly picked up something new from right here. I did however expertise a few technical issues using this web site, as I experienced to reload the website a lot of times previous to I could get it to load properly. I had been wondering if your hosting is OK? Not that I’m complaining, but slow loading instances times will sometimes affect your placement in google and could damage your high quality score if advertising and marketing with Adwords.

  52. Steve Says:

    What superb written report! No idea how you were able to say this text..it’d take me weeks. Well worth it though, I’d assume. Have you considered selling advertising space on your blog?

  53. Christian Says:

    Would be helpful if we relied on what you said

  54. Sara Says:

    Hi guys, I am Sara rch your web site at a minimum three times weekly to read the new stuff you have got. And indeed, I’m so usually motivated with your {amazing|astonishing|astounding|attractive|awesome|beautiful|breathtaking|brilliant|cool

  55. Julio Deras Says:

    Hi! This really is my very first review right here so I just wanted to give a quick scream away and also show you My partner and i truly enjoy studying your site blogposts. Are you able to recommend any other weblogs And internet sites Per message boards that cover the same topics? Regards!

  56. Noemi Reynaga Says:

    As a site owner I believe the pad here’s truly amazing. We appreciate the effort. You must continue the good work once and for all! All the best ..

  57. Genital Warts Treatment In Men Says:

    I’ve been browsing on-line greater than three hours lately, yet I never found any fascinating article like yours. It is pretty value enough for me. In my view, if all site owners and bloggers made good content material as you probably did, the net will be a lot more helpful than ever before.

  58. Leo Lipari Says:

    Thank you for the nice blog. It was really useful for me. Keep sharing such ideas in the future as well. This was actually what I was looking for, and I am glad to came here! Thanks for sharing the such tips with us

  59. Alise Jackstadt Says:

    I admire what you have done right here. I love the part where you say you are doing this kind of to give back but I would assume by all the comments that is working for you as well. Do you have any much more details on this?

  60. Miriam Sobota Says:

    Excellent read, I just passed this kind of onto a colleague that was doing a small research on that. And he actually bought me lunch because I found it for him smile So let me rephrase that.

  61. Charles Dolphin Says:

    I rattling pleased to find this website on bing, just what I was looking for :D likewise saved to favorites.

  62. Lucrecia Elwood Says:

    An incredibly fascinating read, I might not concur completely, but you do make some extremely valid points.

  63. read more Says:

    you are actually a excellent webmaster. The website loading velocity is amazing. It sort of feels that you are doing any unique trick. In addition, The contents are masterpiece. you have done a great process in this matter!

  64. najlepsze kopiarki Says:

    An striking share, I simply given this onto a co-worker who has been performing a little examination on this. And he in truth bought me dinner simply because I found this for him. So allow me reword that: Thank you for the treat!

  65. Airline Job vacancies Says:

    hello there and thank you for your information – I have definitely picked up anything new from right here. I did however expertise a few technical points using this website, since I experienced to reload the web site a lot of times previous to I could get it to load correctly. I had been wondering if your web hosting is OK? Not that I am complaining, but slow loading instances times will sometimes affect your placement in google and can damage your high-quality score if advertising and marketing with Adwords. Anyway I’m adding this RSS to my e-mail and can look out for much more of your respective exciting content. Ensure that you update this again very soon..

  66. pauschalreisen günstig Says:

    this is very nice post. please keep posting

Leave a Reply