share
Stack OverflowCode Chess: Fibonacci Sequence
[+82] [46] SLaks
[2010-02-19 13:46:09]
[ fibonacci ]
[ http://stackoverflow.com/questions/2296664] [DELETED]

Building upon the proven success of Code Golf [1], I would like to introduce Code Chess [2].

Unlike Code Golf, which strives for concision, Code Chess will strive for cleverness.

Can you create a clever or unexpected Fibonacci generator?

Your code must print or return either the nth Fibonacci number or the first n Fibonacci numbers.

Note that I'm not asking for unreadable code; this is not the IOCC. - SLaks
I like the idea, but I get the feeling this will get bombed into oblivion, it took long enough to get code golf to be an accepted 'question' type. - Ed Woodcock
(33) +1, why all the downvotes? Its a community wiki and code golf seems popular in the community (although i dislike it myself; it doesnt belong here). While this, apparently, is code chess they are the same in spirit. That is a "small coding contest". Striving for separate definitions would be splitting hairs. If code golf is OK, so is this. - mizipzor
(10) @ mizipzor lots of us don't think code golf is ok. - anon
(20) Guys, lighten up. It's interesting to see problems solved in a variety of different ways. If you don't like the golf then just ignore the article. - Sean
(3) How does one measure "cleverness" ? imho, this is gonna get closed, for subjectiveness/argumentness/too vague/... - ldigas
(8) @Idigas - By the amount of people who upvote it going "Heh, thats pretty cool". - Kyle Rozendo
Err.. why the code-golf tag? - Zaid
(6) This (and the several other "well, since code-golf is OK, I'm introducing..." questions we've seen recently) are why code-gold should never have been acceptable in the first place. Now we reap what we have sown. I am officially saying "I told you so." - dmckee
(11) @Neil Butterworth: Moreover, code golf is reasonably objective. An answer can be checked for correctness and the characters counted. "Clever" and "unexpected" are subjective and difficult to define. So, I think this is considerably less suited for SO than code golf. - David Thornley
@Idigas: Clever could be producing the correct result in a non-obvious way, one that requires a bit of thinking to understand. - Skizz
I can't believe no-one's done this at compile time yet (Template meta-programming) - SLaks
@SLaks: Because compile-time solutions are usually boring. - KennyTM
(5) -1: I reckon you should get over to www.stackexchange.com and set up a code golf/chess/project euler clone if that's what you want, I don't think these sort of questions belong here, CW or no. Just my two pence worth. - Ninefingers
@Ninefingers: Ask for a feature-request to have 'ignored tags' actually hide those questions containing the tags. - MikeyB
(1) @MikeyB you already can under your user profile - click your name at the top, go to prefs where you've got the tabs below your profile and select hide ignored tags. - Ninefingers
So how about someone comes with an acceptable umbrella tag that covers code-golf, code-chess, etc, so those who want to ignore it all, can. - skaffman
(1) I'd suggest: code-sports - MicSim
(1) This is actually more appropriate for mathoverflow. Should the sequence arise in a truely unexpected place it would be an interesting mathematical result and an actual implementation is just a detail. Obscure (dare I say stupid) use of programming constructs is just that, and there really is no suprise. - phkahler
Chess is actually same as golf - if you can kill in 1 move, then go for it. I would call this code Halloween instead. - Hamish Grubijan
(5) I wish there is "Code Tennis", where you write a good code, then your opponent improves it, and you must improve it again or else you lose. - SHiNKiROU
(1) ah, another tag to hide. thanks. given the massive upvotes for the silly answers, this will probably not go as you might have expected. - Steven A. Lowe
(2) Why do we need a code-chess version if there's already a code-golf version? Answer: we don't. - gnovice
(1) If this had been tagged [code-golf] instead of [code-chess], it would probably not have been closed, because those who don't like code-golf would have [code-golf] in their Ignored tags list, and would never notice this post in the first place... - awe
[+65] [2010-02-21 23:22:33] Juliet

OpenOffice Calc / MS Excel

A1: 1 A2: 1 A3: =A1 + A2:

Grab handle of A3

And fill down


I like this one!!! - Yin Zhu
I should tell this trick to my grade 10 math teacher, because other students are having trouble with recursive sequences. - SHiNKiROU
(1) Memoization, anyone? - Matt Ball
1
[+47] [2010-02-19 13:52:50] forki23
int i = 0;
while(true)
{
  Console.WriteLine(i);
  Console.WriteLine(i);
  i = i + 1;
}

It should print the "first n Fibonacci numbers" (and some numbers more :-) ).


(42) +1 for cheating - SLaks
(13) This only prints the number 1 one time. - mob
(3) works for me in C# - forki23
@mobrule: So, Console.WriteLine(i); Console.WriteLine(i); i ++; - KennyTM
What a waste of WriteLine calls! What's wrong with int i = 1; Console.WriteLine(i); while (true) { Console.WriteLine(i); i = i+1; }? - Matt Ball
(2) -1 for cheating - Josh
(1) what's wrong with Console.WriteLine(i++)? what a waste of lines - Nico
2
[+45] [2010-02-19 17:33:59] MikeyB

Regular expression

(I can't take credit for this thing of beauty - see source: perlmonks [1])

perl -le'$n=shift;$==0,(1x$_)=~/^(1|11(??{}))*$(?{$=++})^/,print$=for 0..$n-1' 7

Output:

1
1
2
3
5
8
13
[1] http://www.perlmonks.org/?node_id=813858

(2) +1 because this is totally insane! - Danilo Piazzalunga
+1 for making my head hurt! - A. Levy
(3) The runtime may be horrible, but this is the only bignum implementation I see here… the others all overflow at 32 or 64 bits. - Potatoswatter
@Potatoswatter, do you really want people to write code which works for large integers? This is just silly. The intent was to see clever code/approaches. - Moron
(2) @Moron: those goals are incompatible? Getting anywhere with the fibonacci sequence requires bignums. Need to raise the bar a little to keep this interesting… and there's no point in using native integers when they impose such strict limitations. - Potatoswatter
(3) I guess this would be a good answer for a code golf... but perhaps not for a code chess ! - Thomas Levesque
(1) My eyes ... MY EYES! - Tim Post
@Potato: I disagree. Most algorithms here can very easily be converted to use integers of the right size. Trying to impose the limitation you speak of is pointless. - Moron
(1) @Moron: There are no limitations, it's an open ended problem. You can't fault people who do gracefully handle the exponential growth. (Erm, in terms of storage anyway ;v) .) - Potatoswatter
@Potato: Not faulting anyone. In fact, to me it seems you are doing the opposite: faulting people who don't try to handle all. fwiw, this was the first answer I gave a +1 to! - Moron
(10) Looks just like all the other perl code I've seen here ;-) - phkahler
laugh, no wonder a NASA guy developed Perl. It shows. - Axonn
3
[+39] [2010-02-20 03:08:23] mocj

Maybe I read too literally?

std::string Fibonacci(unsigned n)
{
   return "either the nth Fibonacci number or the first n Fibonacci numbers.";
}

(26) +1 for sheer cheek - Platinum Azure
(18) -1 for sheer cheek - Yuval Adam
(4) I added +1 for mocj's answer and voted for Yuval's comment. Should these votes cancel each other? - lmsasu
4
[+37] [2010-02-19 14:53:22] jleedev

Brainf*ck

+>+< [ >.< [>+>+<<-]> ]

Hex dump of output:

0101020305080d1522375990e97962db3d18556dc22ff12011314273b528dd05e2e7c9b07929a2cb
6d38a5dd825fe140216182e36548adf5a29739d009d9e2bb9d58f54d428fd1603191c25315687de5
6247a9f0998922abcd7845bd02bfc18041c102c3c5884dd522f719102939629bfd98952dc2efb1a0
51f1423375a81dc5e2a78930b9e9a28b2db8e59d821fa1c0612182a325c8edb5a257f9504999e27b
5dd8350d424f91e07151c213d5e8bda562076970d949226b8df8857d027f

The first n fibonacci numbers modulo 256, where n = 190.


(27) I like the >.< smiley on the center~ - GaiusSensei
(3) YEARGHHH! Actually solving any given problem in BF is... awesome. :-D - DevSolar
5
[+33] [2010-02-19 13:48:58] SLaks

C#

Who said constructors cannot be recursive? [1]

struct FibonacciNumber {
    const int InitialValue = 1;

    public FibonacciNumber(int index) : this(index == 0 ? new FibonacciNumber() : new FibonacciNumber(index - 1)) { }
    public FibonacciNumber(FibonacciNumber previous) : this(previous.Current, previous.previous + previous.Current) { }
    FibonacciNumber(long previous, long current) { this.previous = previous; this.current = current - InitialValue; }

    readonly long previous;
    long current;
    public long Current { get { return current + InitialValue; } }

    public override string ToString() { return Current.ToString(); }
}
[1] http://msdn.microsoft.com/en-us/library/1w8stdbt.aspx

(5) +1 Thats silly, but really cool. :P - Kyle Rozendo
(2) +1, that is awesome! - John Gietzen
6
[+26] [2010-02-19 14:13:49] KennyTM
#!/usr/bin/env python3.1

from urllib.request import urlopen

print ("Please enter which Fibonacci number you wish to compute:", end=" ")
n = int(input())

seq = "A000045"

url = "http://www.research.att.com/~njas/sequences/?q=id%3a" + seq + "&p=1&n=10&fmt=3"
resp = urlopen(url)

values = []

for line in resp:
    if line[:2] in [b'%S', b'%T', b'%U']:
        numbers = line.split(b' ')[-1].split(b',')
        values += [int(val) for val in numbers if val != b'\n']


ordinal = "th"
if (1 <= n%10 <= 3) and not (11 <= n%100 <= 13):
    ordinal = ["st", "nd", "rd"][(n-1)%10]
ordinal = str(n)+ordinal

if n < len(values):
    print ("The", ordinal, "Fibonacci number is", values[n])
else:
    print ("The Internet is incapable of computing the", ordinal, "Fibonacci number yet, please come back later.")       

OK, the normal version:

import math

def fib(n):
   sqrt5 = math.sqrt(5)
   return int(round(((sqrt5+1)/2)**n / sqrt5))

(2) Very clever. Very much in the spirit of the notion, I think. - Beska
7
[+24] [2010-02-19 13:56:54] SLaks

I once did this in Word field codes, but I'm not sure how to post it. (Ctrl+C will not copy Word field codes)

EDIT: Here's a screenshot:

Fibonacci Field Codes

Once it gets past 1023341553, Word crashes.

EDIT: I uploaded the original document [1].

[1] https://docs.google.com/uc?export=download&id=0B188SCxZIw27ODYzNGRkODYtMmE3NC00ZjdkLTliZDUtZmZjYWY1ZGNiNmVk

Is there somewhere that I can upload the original document? - SLaks
@Slaks: Google docs - OscarRyz
(1) @Oscar: Does Google Docs support field codes? - SLaks
It does, but they don't work correctly. However, you can download the original here: docs.google.com/… - SLaks
(2) I'm scared now. In normal mode, after 1023341553, it cycles 5, 8, 3 ... forever. When I switch to print preview, it gives incorrect seven-digit numbers, presumably just truncated for display, after 9227465. - jleedev
If you select the 5, 8, 3's and click Update Field, Word will crash. I don't know why it would give incorrect numbers; try updating all field codes (afer deleting the 5, 8, 3's). - SLaks
(3) Once it gets past 1023341553, Word crashes: +1 - FUZxxl
8
[+24] [2010-02-20 02:51:16] Dejw

C++ Template Language

Nth Fibonacci number calculated at compilation time:

template<int N> struct Fib {
  static const int result = Fib<N-1>::result + Fib<N-2>::result;
};

template<> struct Fib<0> {
  static const int result = 0;
};

template<> struct Fib<1> {
  static const int result = 1;
};

#include <iostream>
int main(void){
  std::cout << "Fib(10) = " << Fib<10>::result << std::endl;
  return 0;
}

(4) Nice one. Really like the use of templates. Great fun to compile this changing 10 to 1 000 000:P - martiert
I think C++ template has a recursion depth limit, I've tried the factorial metaprogram before. - SHiNKiROU
9
[+23] [2010-02-19 19:26:19] KennyTM

Not clever, just have some fun :).

To run:

gcc the_file.c -DN=7
./a.out

Requires gcc and support for POSIX's printf positional specifier support.


#include<stdio.h>
int main() {
    int n = N;
    if (n >= 2) {
        int r, t;
        char x[34],*s =
        "#include<stdio.h>%2$c"
        "int main() {"
            "int n = N;"
            "if (n >= 2) {"
                "int r, t;"
                "char x[34],*s = %3$c%1$s%3$c;"
                "sprintf(x, %3$cgcc -DN=%%d -x c -%3$c, n-1);"
                "FILE* f = popen(x, %3$cw%3$c);fprintf(f,s,s,10,34);pclose(f);"
                "f = popen(%3$c./a.out%3$c, %3$cr%3$c);fscanf(f,%3$c%%d%3$c, &r);pclose(f);"
                "sprintf(x, %3$cgcc -DN=%%d -x c -%3$c, n-2);"
                "f = popen(x, %3$cw%3$c);fprintf(f,s,s,10,34);pclose(f);"
                "f = popen(%3$c./a.out%3$c, %3$cr%3$c);fscanf(f,%3$c%%d%3$c, &t);pclose(f);"
                "n = r+t;"
            "}"
            "printf(%3$c%%d%3$c, n);puts(%3$c%3$c);"
            "return 0;"
        "}";
        sprintf(x, "gcc -DN=%d -x c -", n-1);
        FILE* f = popen(x, "w");fprintf(f,s,s,10,34);pclose(f);
        f = popen("./a.out", "r");fscanf(f,"%d", &r);pclose(f);
        sprintf(x, "gcc -DN=%d -x c -", n-2);
        f = popen(x, "w");fprintf(f,s,s,10,34);pclose(f);
        f = popen("./a.out", "r");fscanf(f,"%d", &t);pclose(f);
        n = r+t;
    }
    printf("%d", n);puts("");
    return 0;
}

+1 Nice, a series of C programs: each program creates and compiles its successor! Wow. Let's try mathematical induction on the code... - nalply
10
[+21] [2010-02-19 15:13:01] Yuval Adam

Using Binet's formula [1] (though not the original version rather a slightly altered one) you can calculate the nth fibonacci number directly - no recursion, no iteration:

PHI = (1 + 5**0.5) / 2 # golden ratio

def F(n):
    return int(PHI**n / 5**0.5)

Important to note that due to Loss of Significance [2] you can't calculate really large numbers (dependent on floating point implementation).

[1] http://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html
[2] http://en.wikipedia.org/wiki/Loss_of_significance

(1) Clever, creative. - Beska
(39) I'm not sure using Binet's formula counts as cleverness unless you are in fact Jacques Philippe Marie Binet. - Robert Davis
(9) @Robert - I never took credit for this. Neither am I arrogant to think this code chess will help me, or anyone else, devise a better method for finding Fibonacci numbers which mathematicians have somehow overlooked for centuries. - Yuval Adam
(1) This answer would be clever if you worked out the bounds for how much precision you need to get the Nth Fibonacci number and even moreso if you implemented simplified arbitrary-precision code that's optimized for the task. - R..
(1) @Robert: it's far less obvious to your average Joe than any of the "clever" versions that currently have more votes. (Except the perl regex version.) - Ken Bloom
11
[+19] [2010-02-19 14:07:40] SLaks

C#

Just one statement!

Enumerable.Repeat(new List<long>(32){ 1, 1 }, 1)
    .First(fib => Enumerable.Range(0, 32).Aggregate(true, (u1, u2) => { fib.Add(fib.Last() + fib[fib.Count - 2]); return true; }))

I actually count 3 statements. Still nice though. - Dykam
Just for the fun, I rewrote your snippet to haXe: actionscript.pastebin.com/zCE8s6ZZ - Dykam
12
[+16] [2010-02-19 18:03:37] Robert Davis
int Fib(int n)
{
   if(n > 46)
      throw new ArgumentOutOfRangeException("n");
   if(n == 46)
      return 1836311903;
   else if(n == 45) 
      return 1134903170;
   else
      return Fib(n + 2) - Fib(n + 1);
}

This will probably blow your stack.

Fibonacci numbers n > 46 will overflow a 32 bit int.


(1) It doesn't work; you need to add else if(n == 45) return 1134903170; - SLaks
recursing up... i like it - jon_darkstar
13
[+15] [2010-02-20 02:03:26] Carlos Gutiérrez

AntiChess: Windows cmd

This is probably the slowest, least elegant, most resource intensive of the answers. It works for 0 to full disk.

type fibo.cmd

@echo off
type nul>a
if "%1"=="0" goto :done
type nul>b
<nul (set/p z=1) >a
<nul (set/p z=1) >i
:loop
copy /b a c >nul
copy /b b+c a >nul
copy /b c b >nul
<nul (set/p z=1) >>i
call :size i
if /i %s% LSS %1 goto loop
:done
call :size a
echo The %1th Fibonacci number is %s%
del a
if exist b del b
if exist c del c
if exist i del i
:size
set s=%~z1

C:\fibo>fibo 20
The 20th Fibonacci number is 6765

Yes, I know SET /A:

@set a=1&set b=0&for /l %%i in (2,1,%1)do @set/ac=a&set/aa=b+c&set/ab=c
@echo %a%

(2) +1 Evil........ - SLaks
For the set /a variant you don't need delayed expansion. set /a automatically expands variable names even without % or !. - Joey
@Johannes - True, I didn't know it at the time. Updated, thanks. - Carlos Gutiérrez
14
[+9] [2010-03-09 03:25:51] Carlos Gutiérrez

dc [1] in stack

?k1d[sBdlBrlB+zK>L]dsLxf

Instead of printing the numbers as they are calculated, it adds them in order to the stack and dumps the whole stack at the end.

dc uses bignum arithmetic. I tested with 10,000 numbers. The 10,000th number is 2,090 digits long.

Works for n > 2.

And it's only 24 chars long.

dc -f fibo.dc
15
610
377
233
144
89
55
34
21
13
8
5
3
2
1
1
[1] http://linux.die.net/man/1/dc

15
[+5] [2010-02-19 17:05:29] Moron

Here is one in C# which uses the fact that 5f^2 +- 4 is a perfect square if and only if f is a fibonacci number. This one prints a list of fibonacci numbers in sequence.

void PrintFib(int n) {
    if (n < 1) return;

    Dictionary<int, int> squares = new Dictionary<int, int>();

    int count = 1;
    Console.WriteLine("1");

    int i = 1;
    while (count < n) {
        int sqr = i * i;

        int x = -1;

        if ((sqr - 4) % 5 == 0) {
            x = (sqr - 4) / 5;
        }

        if ((sqr + 4) % 5 == 0) {
            x = (sqr + 4) / 5;
        }

        if (squares.ContainsKey(x)) {
            Console.WriteLine(squares[x]);
            count++;
        }

        squares[sqr] = i;
        i++;
    }

16
[+4] [2010-02-19 16:00:14] Skizz

In assembler, wrapped into a C/C++ function (compiled with DevStudio 2005):

int Fibonacci (int i)
{
  __asm
  {
    mov eax,0
    mov ebx,1
    mov ecx,i
l1: add eax,ebx
    xchg eax,ebx
    loop l1
  }
}

Not familiar with x86 assembler, so maybe this is obvious, but how is the return value specified here? Perhaps ebx always has the return value on exiting from a function? - A. Levy
ebx is ret value in x86 - Yuval Adam
(1) Actually, DevStudio specifies the return value to be in EAX for integral types. Of course, this is compiler specific, but most IA32 compilers would follow the same convention. - Skizz
17
[+4] [2010-02-19 14:08:34] ChrisQuignon

As in the fibonacci code golf [1], i would like to suggest some examples from the haskell webpage [2].

One from the link above:

f=0:1:zipWith(+)f(tail f)

one with nice code:

fibs = scanl (+) 0 (1:fibs)
fibs = 0 : scanl (+) 1 fibs

and one with good old math:

fib n = round $ phi ** fromIntegral n / sq5
  where
    sq5 = sqrt 5 :: Double
    phi = (1 + sq5) / 2
[1] http://stackoverflow.com/questions/232861/fibonacci-code-golf
[2] http://www.haskell.org/haskellwiki/The_Fibonacci_sequence

18
[+4] [2010-02-24 18:26:06] gbn

Now you procedural code monkeys have finished at your typewriters... time for some Shakespeare [1] (no, not the language based on keywords like "codpiece")

It's a recursive set based operation

DECLARE @Limit int

SELECT @Limit = 10

;WITH cFoo AS
(
    SELECT 0 as n, CAST(0 as bigint) AS x, CAST(1 as bigint) AS y
    UNION ALL
    SELECT n+1, y, x + y FROM cFoo WHERE n+1 < @Limit
)
SELECT
    cFoo.x
FROM
    cFoo
OPTION (MAXRECURSION 0)

Edit: SQL Server 2005+. It can be done in other dialects too

[1] http://en.wikipedia.org/wiki/Infinite_monkey_theorem

(4) I thought you mean Shakespeare the language en.wikipedia.org/wiki/Shakespeare_%28programming_language%29 - KennyTM
@KennyTM: oh very droll... :-) - gbn
19
[+3] [2010-09-14 03:13:22] Timwi

Shortest C# solution so far

Enumerable.Range(0, n).Aggregate(new { a = 1, b = 0 },
    (a, b) => new { a = a.b, b = a.a + a.b }).b;

I know this is not code golf. I thought it was clever nonetheless :)


20
[+3] [2010-02-22 13:07:38] TheSoftwareJedi
public class FibonacciSequence : IEnumerable<ulong>
{

    public IEnumerator<ulong> GetEnumerator()
    {
        yield return 0;
        yield return 1;
        ulong a = 0;
        ulong b = 0;
        ulong c = 1;
        checked
        {
            while (true)
            {
                a = b;
                b = c;
                try
                {
                    c = a + b;
                }
                catch (OverflowException)
                {
                    yield break;
                }
                yield return c;
            }
        }
    }

    System.Collections.IEnumerator 
         System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

21
[+3] [2010-02-22 15:03:58] consultutah

This my favorite solution:

private readonly static double rootOfFive = Math.Sqrt(5); 
private readonly static double goldenRatio = (1 + rootOfFive) / 2; 

internal static int GetFinbonacciValue(int number) 
{ 
    return Convert.ToInt32((Math.Pow(goldenRatio, number) - Math.Pow(-goldenRatio, -number)) / rootOfFive); 
}

22
[+2] [2010-03-01 11:26:28] leChuck

Python generator:

def fibonacci():
    n, m = 0, 1
    while True:
        yield n
        n, m = m, n + m

Called n times.


23
[+2] [2010-02-19 17:28:48] Moron

Here is another one in C# using the fact that

f(2n) = (2f(n-1) + f(n))* f(n)

f(2n-1) = f(n)^2 + f(n-1)^2.

Gives an O(logn) time algo to find just the nth fibonacci number (and some extra as a side effect), just like the matrix version.

// Computes fib(n) and fib(n-1).
void FibPair(int n, out int Fn, out int Fn_minus_1) {
    Fn = 1;
    Fn_minus_1 = 1;
    if (n <= 2) return;

    int f_n, f_n1;

    if ((n % 2) == 0) {

        FibPair(n / 2, out f_n, out f_n1);
        Fn = (2 * f_n1 + f_n) * f_n;
        Fn_minus_1 = f_n * f_n + f_n1 * f_n1;
        return;
    }

    FibPair((n + 1) / 2, out f_n, out f_n1);

    Fn = f_n * f_n + f_n1 * f_n1;
    Fn_minus_1 = (2 * f_n - f_n1)*f_n1;
}

24
[+2] [2010-02-19 14:03:55] Sean

Here's one that uses memoization (a common functional technique) to recursively calculate and cache intermediate values. It uses lambdas and higher order functions to generate the Nth number in the sequence. When you do something like Fib(50) this can make a big difference:

    static long Fib(long number)
    {
        Func<long,long> fib=null;

        fib=Memorize<long,long>(value=>
        {
            if(value==0) return 0;
            if(value==1) return 1;

            return fib(value-1)+fib(value-2);
        });

        return fib(number);
    }

    static Func<T,R> Memorize<T,R>(Func<T,R> lookup)
    {
        Dictionary<T,R> cache=new Dictionary<T,R>();

        Func<T,R> memo=value=>
        {
            R result;
            if(cache.TryGetValue(value,out result)==false)
            {
                result=lookup(value);
                cache.Add(value,result);
            }

            return result;
        };

        return memo;
    }

25
[+2] [2010-05-17 04:44:36] TiuTalk

PHP

<?php
$cache = array(0, 1, 1);
function fib($n) {
    global $cache;

    return (isset($cache[$n])) ? $cache[$n] : ($cache[$n] = fib($n - 2) + fib($n - 1));
}
?>

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


26
[+2] [2010-05-23 17:17:32] Stephen Swensen

In F#, using an infinite tail-recursive sequence.

let fibseq =    
    let rec fibseq n1 n2 = 
        seq { let n0 = n1 + n2 
              yield n0
              yield! fibseq n0 n1 }
    seq { yield 1I ; yield 1I ; yield! (fibseq 1I 1I) }

let fibTake n = fibseq |> Seq.take n //the first n Fibonacci numbers
let fib n = fibseq |> Seq.nth (n-1) //the nth Fibonacci number

27
[+1] [2010-02-24 22:05:45] sth

A less common way to calculate Fibonacci numbers:

def fib(n):
   i = j = 1.0
   for _ in range(n):
      j *= i
      i = 1 / i + 1
   return int(j)

28
[+1] [2010-07-07 09:18:11] phimuemue

Here's a program in C:

#include<stdio.h>
#define N 0
#define FNMINUSONE 1
#define FNMINUSTWO 0
char*c="#include<stdio.h>%c#define N 0%c#define FNMINUSONE %d%c#define FNMINUSTWO %d%cchar*c=%c%s%c;%cint main(int argc, char*argv[]){%c  int n=atoi(argv[1]);FILE*f=fopen(%cfibo.c%c,%cw%c);%c  printf(c,10,10,FNMINUSONE+FNMINUSTWO,10,FNMINUSONE,10,34,c,34,10,10,34,34,34,34,10,10,34,34,34,34,10,10);fprintf(f,c,10,10,FNMINUSONE+FNMINUSTWO,10,FNMINUSONE,10,34,c,34,10,10,34,34,34,34,10,10,34,34,34,34,10,10);%c  fclose(f);if(n>1){system(%cgcc -o fibo fibo.c%c); char s[80];sprintf(s,%c./fibo %%d%c,n-1);system(s);}%c}%c";
int main(int argc, char*argv[]){
  int n=atoi(argv[1]);FILE*f=fopen("fibo.c","w");
  printf(c,10,10,FNMINUSONE+FNMINUSTWO,10,FNMINUSONE,10,34,c,34,10,10,34,34,34,34,10,10,34,34,34,34,10,10);fprintf(f,c,10,10,FNMINUSONE+FNMINUSTWO,10,FNMINUSONE,10,34,c,34,10,10,34,34,34,34,10,10,34,34,34,34,10,10);
  fclose(f);if(n>1){system("gcc -o fibo fibo.c"); char s[80];sprintf(s,"./fibo %d",n-1);system(s);}
}

Compile: gcc -o fibquine fibquine.c

Start: ./fibquine 10 (for the 10th fibonacci number)

The program computes the fibonacci number the following way: It reproduces its own source code, but with other constants (needed for the fibonacci calculation), then compiles the newly generated source code and reruns the program recursively (i.e. it gets compiled again, run again, compiled again, run again, and so on). Note that I run it under Ubuntu 10.04 and did not test it with other operating systems.

Cleverness of the program is disputable, but I think it's definitely unexpected.


I like it, but KennyTM beat you to it. - SLaks
29
[+1] [2010-07-30 20:33:05] geckodru

F# Using Seq.unfold

let fib n =
  Seq.nth n (Seq.unfold 
    (fun (c, n) -> Some(c, (n, c + n)))
    (0L, 1L))

30
[+1] [2010-02-19 15:35:57] just_wes
void print_fib(int n) {
    int fibs[2];
    fibs[0] = fibs[1] = 1;

    for (int i = 0; i < n; i++) {
        printf("%d\n", fibs[i % 2]);
        fibs[i % 2] += fibs[(i - 1) % 2];
    }
}

Currently does one more calculation than necessary.


31
[+1] [2010-02-19 15:53:32] jmbr

MATLAB

function f = fib(n);
if n > 2
    z = [0 1; 1 1]^(n-1)*ones(2, 1);
    f = z(1);
else
    f = 1;
end

32
[+1] [2010-02-19 19:08:49] cobbal

go:

package main

import fmt "fmt"

func halfFib(co, out chan int) {
    a := 0
    for {
        a += <-co
        out <- a
        co <- a
    }
}

func main() {
    co := make(chan int)
    out := make(chan int)
    go halfFib(co, out)
    go halfFib(co, out)
    co <- 1
    n := <-out
    for n > 0 {
        fmt.Println(n)
        n = <-out
    }
}

33
[+1] [2010-02-19 19:20:24] George Jempty

Javascript:

Sent this in for a Javascript position with a game software company recently. I'd never implemented Fibonacci numbers but immediately recognized them. My implmentation is non-recursive and completely of my own devising though I'm presuming its a known solution. They actually flew me up for an in person interview so I'm guessing the following isn't too awful:

(2) In JavaScript, write a recursive function that will print out the following output:

0 1 1 2 3 5 8 13 etc.

I know enough about what recursion is to know that it can be problematic from a resource (memory) consumption perspective particularly in a language that does not implement proper tail recursion, and I don't think Javascript does (but I do know that Lua does!). I also recognize this as a Fibonacci sequence, but I can't remember the recursive solution, but can certainly provide a non-recursive solution, replete with input validation using a regular expression. If the implementation seems odd, please bear in mind that I've never implemented this algorithm before so this solution is completely of my own devising.

<script> 
function fibseq(iter) { 
  if (!/^\d+$/.test(iter)) { 
      alert("Please retry generating Fibonacci numbers with input of 0 or a positive integer"); 
      return; 
    } 

    var fibseq = []; 

    for (var i=0; i<=iter; i++) { 
        if (i<=1) { 
          fibseq.push(i); 
        } 
        else { 
          fibseq.push(fibseq[i-1] + fibseq[i-2]); 
        } 
    } 

    alert('fibseq(' + iter + '): ' + fibseq.join(' ')); 
} 

fibseq(7); 
</script>

This is equivalent to my C# one-liner. (Which was also my original algorithm) - SLaks
34
[+1] [2010-02-21 15:25:28] liori

IPython, O(log n) with exact bigint results (by matrix powers), lambda-style. Who said python ought to be readable?

In [1]: mult = lambda ((a,b),(c,d)),((e,f),(g,h)):((a*e+b*g, a*f+b*h), (c*e+d*g, c*f+d*h))

In [2]: power = lambda m,n:(m) if (n==1) else (power(mult(m,m), n/2) if (n%2==0) else mult(power(mult(m,m), n/2), m))

In [3]: map(lambda n:power(((0,1),(1,1)), n), xrange(1,10))
Out[3]: 
[((0, 1), (1, 1)),
 ((1, 1), (1, 2)),
 ((1, 2), (2, 3)),
 ((2, 3), (3, 5)),
 ((3, 5), (5, 8)),
 ((5, 8), (8, 13)),
 ((8, 13), (13, 21)),
 ((13, 21), (21, 34)),
 ((21, 34), (34, 55))]

35
[+1] [2010-03-03 17:34:46] Jasarien

Python

a,b = 0,1
while b:
    print a,
    a,b = b,a+b

Nice and short. Prints as many fib numbers as your computer has ram to store... I guess.


36
[+1] [2010-02-24 00:31:15] Danilo Piazzalunga

A Python solution. Uses a time-memory tradeoff to achieve efficency!

print """import sys

fib = ["""

a, b = 0L, 1L
for i in range(1000):
    print "    %d," % a
    a, b = b, a + b

print """]

n = int(sys.argv[1])
print fib[n]"""

37
[0] [2010-03-08 16:07:34] Aaron
begin

declare @cnt int; set @cnt = 2;
declare @fibs table(fib bigint, sequence int); insert into @fibs select 0,1 union select 1,2;  

while(@cnt<93) begin
    set @cnt = @cnt + 1
    insert into @fibs
    select sum(fib), @cnt from @fibs where sequence > @cnt-3
end

select * from @fibs

end

38
[0] [2010-03-09 02:17:30] MPelletier

J [1] has of course a whole lot of smart ways to tackle this (see http://www.jsoftware.com/jwiki/Essays/Fibonacci%20Sequence)

However, I came upon this almost by accident and I enter it as an "anti-code-chess" answer. Meaning that it's really dumb:

fib =: 3 : 0
    if. y <: 1 do.
        y
    else.
        (fib y-1)+(fib y-2)
    end.
)

While potentially dangerous in many languages, in J it's system halting dumb. Do not try this with 100 unless you are ready to kill a very voracious process

[1] http://www.jsoftware.com

39
[0] [2010-02-19 17:32:25] oxbow_lakes

Scala:

Thanks to scalaz [1]

val fibs = (0,1).iterate[Stream]( i => i._2 -> (i._1 + i._2)).map(_._1) //infinite stream

And so:

fibs.take(10).foreach(println(_))

Or from scratch without the higher-kinded type cleverness:

case class Streamable[A](val start: A) {
  def stream(f : A => A) : Stream[A] = Stream.cons(start, Streamable(f(start)).stream(f))
}
implicit def any2streamable[A](a: A) = new Streamable(a)

val fibs = (0,1).stream( i => i._2 -> (i._1 + i._2)).map(_._1)
[1] http://code.google.com/p/scalaz/

40
[0] [2010-02-20 01:39:28] pdr

A little bit of Linq cheekiness anyone?

// Edit: Forgot these three lines
var sqrt5 = Math.Sqrt(5);
var a = (1 + sqrt5)/2;
var b = (1 - sqrt5)/2;

foreach (var d in new object[n].Select((o, i) => (int)((Math.Pow(a, i + 1) - Math.Pow(b, i + 1)) / (a - b))))
{
    Console.WriteLine(d);
}

41
[0] [2010-02-19 14:53:02] Tor Valamo

Erlang:

Prints n first numbers:

-module(fib).
-export([fib/1]).

fib(C) -> fib(1, 1, C).  
fib(_, _, 0) -> ok;
fib(N, M, C) -> io:fwrite("~p~n", [N]), fib(M, N+M, C-1).

Returns n first numbers

-module(fib).
-export([fib/1]).

fib(C) -> fib(1, 1, [], C).
fib(_, _, A, 0) -> lists:reverse(A);
fib(N, M, A, C) -> fib(M, N+M, [N|A], C-1).

42
[0] [2010-09-14 03:29:45] Zurahn

JavaScript

var x = 6;
document.write((function(n){
    return n <= 1 ? n : arguments.callee(n-1)+arguments.callee(n-2);
})(x)); // outputs 8

43
[0] [2010-04-28 13:03:39] Jesper

Another recursive one in Scala:

def fib: Stream[Int] =
  Stream.cons(0, Stream.cons(1, (fib zip fib.tail) map { case (p, q) => p + q }))

Defines an infinite sequence of Fibonacci numbers. Try printing the first few elements with:

fib take 20 print

It creates a stream by starting with 0 and 1. Then the tail is made in two steps:

  1. (fib zip fib.tail) uses the zip operation, which creates a sequence of pairs from corresponding elements from fib and fib.tail. That sequence will look like: [(0, 1), (1, 2), (2, 3), (3, 5), ...]
  2. That sequence is mapped using the inline function { case (p, q) => p + q } to add the two numbers in each pair, forming the tail of the sequence: [1, 3, 5, 8, ...]

The result is a stream producing the Fibonacci sequence [0, 1, 1, 3, 5, 8, ...]


44
[0] [2010-06-24 03:42:46] Hamish Grubijan

Python: print("1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...") Also, a clever way would be to perform image processing on these images: http://www.google.com/images?hl=en&safe=off&q=fibonacci%20sequence%20in%20nature&um=1&ie=UTF-8&source=og&sa=N&tab=wi [1]

[1] http://www.google.com/images?hl=en&safe=off&q=fibonacci%20sequence%20in%20nature&um=1&ie=UTF-8&source=og&sa=N&tab=wi

45
[0] [2010-05-23 14:17:34] dzs

SWI-prolog. It works with arbitrary precision integers.

fibolist(N, R) :- fibohelper(N, 1, 1, [1, 1], R).
fibohelper(0, _, _, R, R).
fibohelper(N, F2, F1, PR, R) :- N > 0, F is F2 + F1, N1 is N - 1, append(PR, [F], RR), fibohelper(N1, F1, F, RR, R).

And the call:

2 ?- fibo2list(100, R).
R = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074, 32951280099, 53316291173, 86267571272, 139583862445, 225851433717, 365435296162, 591286729879, 956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723, 17167680177565, 27777890035288, 44945570212853, 72723460248141, 117669030460994, 190392490709135, 308061521170129, 498454011879264, 806515533049393, 1304969544928657, 2111485077978050, 3416454622906707, 5527939700884757, 8944394323791464, 14472334024676221, 23416728348467685, 37889062373143906, 61305790721611591, 99194853094755497, 160500643816367088, 259695496911122585, 420196140727489673, 679891637638612258, 1100087778366101931, 1779979416004714189, 2880067194370816120, 4660046610375530309, 7540113804746346429, 12200160415121876738, 19740274219868223167, 31940434634990099905, 51680708854858323072, 83621143489848422977, 135301852344706746049, 218922995834555169026, 354224848179261915075, 573147844013817084101, 927372692193078999176] .

prolog is great, isn't it? :D


46