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

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.

link|improve this question
34  
+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 Feb 19 '10 at 13:52
10  
@ mizipzor lots of us don't think code golf is ok. – anon Feb 19 '10 at 13:58
21  
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 Feb 19 '10 at 14:05
9  
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 Feb 19 '10 at 15:57
13  
@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 Feb 19 '10 at 15:59
show 21 more comments
feedback

migrated from stackoverflow.com Mar 27 '11 at 14:02

This question came from our site for professional and enthusiast programmers.

closed as not constructive by Shog9 Mar 28 '11 at 4:48

This question is not a good fit to our Q&A format. We expect answers to generally involve facts, references, or specific expertise; this question will likely solicit opinion, debate, arguments, polling, or extended discussion. See the FAQ for guidance on how to improve it.

46 Answers

1 2

OpenOffice Calc / MS Excel

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

Grab handle of A3

And fill down

link|improve this answer
I like this one!!! – Yin Zhu Mar 9 '10 at 2:19
I should tell this trick to my grade 10 math teacher, because other students are having trouble with recursive sequences. – SHiNKiROU Jul 30 '10 at 20:54
4  
Memoization, anyone? – Matt Ball Aug 12 '10 at 15:34
Priceless :) +1 – Soner Gönül Aug 7 '11 at 14:37
feedback
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 :-) ).

link|improve this answer
54  
+1 for cheating – SLaks Feb 19 '10 at 13:55
15  
This only prints the number 1 one time. – mob Feb 19 '10 at 16:37
3  
works for me in C# – forki23 Feb 19 '10 at 17:19
3  
-1 for cheating – Josh Sep 14 '10 at 20:18
4  
what's wrong with Console.WriteLine(i++)? what a waste of lines – Nico Nov 17 '10 at 20:55
show 2 more comments
feedback

Maybe I read too literally?

std::string Fibonacci(unsigned n)
{
   return "either the nth Fibonacci number or the first n Fibonacci numbers.";
}
link|improve this answer
33  
+1 for sheer cheek – Platinum Azure Feb 20 '10 at 3:25
23  
-1 for sheer cheek – Yuval Adam Feb 20 '10 at 12:48
4  
I added +1 for mocj's answer and voted for Yuval's comment. Should these votes cancel each other? – lmsasu Jun 26 '10 at 10:40
feedback

Regular expression

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

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

Output:

1
1
2
3
5
8
13
link|improve this answer
4  
+1 because this is totally insane! – Danilo Piazzalunga Feb 19 '10 at 19:07
4  
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 Feb 19 '10 at 19:49
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 Feb 20 '10 at 1:55
3  
I guess this would be a good answer for a code golf... but perhaps not for a code chess ! – Thomas Levesque Feb 20 '10 at 2:14
14  
Looks just like all the other perl code I've seen here ;-) – phkahler Feb 22 '10 at 15:12
show 7 more comments
feedback

Brainf*ck

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

Hex dump of output:

0101020305080d1522375990e97962db3d18556dc22ff12011314273b528dd05e2e7c9b07929a2cb
6d38a5dd825fe140216182e36548adf5a29739d009d9e2bb9d58f54d428fd1603191c25315687de5
6247a9f0998922abcd7845bd02bfc18041c102c3c5884dd522f719102939629bfd98952dc2efb1a0
51f1423375a81dc5e2a78930b9e9a28b2db8e59d821fa1c0612182a325c8edb5a257f9504999e27b
5dd8350d424f91e07151c213d5e8bda562076970d949226b8df8857d027f

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

link|improve this answer
34  
I like the >.< smiley on the center~ – GaiusSensei Feb 22 '10 at 13:10
5  
YEARGHHH! Actually solving any given problem in BF is... awesome. :-D – DevSolar Feb 22 '10 at 13:28
feedback

C#

Who said constructors cannot be recursive?

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(); }
}
link|improve this answer
6  
+1 Thats silly, but really cool. :P – Kyle Rozendo Feb 19 '10 at 14:55
2  
+1, that is awesome! – John Gietzen Jun 11 '10 at 15:55
feedback
#!/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))
link|improve this answer
3  
Very clever. Very much in the spirit of the notion, I think. – Beska Feb 19 '10 at 15:22
feedback

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;
}
link|improve this answer
+1 Nice, a series of C programs: each program creates and compiles its successor! Wow. Let's try mathematical induction on the code... – nalply Mar 10 '11 at 11:08
feedback

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.

link|improve this answer
Is there somewhere that I can upload the original document? – SLaks Feb 19 '10 at 14:16
@Slaks: Google docs – OscarRyz Feb 19 '10 at 14:21
1  
@Oscar: Does Google Docs support field codes? – SLaks Feb 19 '10 at 14:32
3  
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. – Josh Lee Feb 19 '10 at 15:10
6  
Once it gets past 1023341553, Word crashes: +1 – FUZxxl Sep 15 '10 at 5:58
show 2 more comments
feedback

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;
}
link|improve this answer
4  
Nice one. Really like the use of templates. Great fun to compile this changing 10 to 1 000 000:P – martiert Jul 7 '10 at 9:34
I think C++ template has a recursion depth limit, I've tried the factorial metaprogram before. – SHiNKiROU Jul 30 '10 at 20:53
feedback

Using Binet's formula (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 you can't calculate really large numbers (dependent on floating point implementation).

link|improve this answer
1  
Clever, creative. – Beska Feb 19 '10 at 15:25
45  
I'm not sure using Binet's formula counts as cleverness unless you are in fact Jacques Philippe Marie Binet. – Robert Davis Feb 19 '10 at 18:17
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 Feb 19 '10 at 18:42
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.. Aug 8 '10 at 14:19
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 Jan 28 '11 at 5:48
feedback
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.

link|improve this answer
2  
It doesn't work; you need to add else if(n == 45) return 1134903170; – SLaks Feb 21 '10 at 15:06
recursing up... i like it – jon_darkstar Dec 15 '10 at 2:36
feedback

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; }))
link|improve this answer
I actually count 3 statements. Still nice though. – Dykam Mar 8 '10 at 16:36
Just for the fun, I rewrote your snippet to haXe: actionscript.pastebin.com/zCE8s6ZZ – Dykam Mar 8 '10 at 21:12
feedback

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%
link|improve this answer
3  
+1 Evil........ – SLaks Feb 21 '10 at 4:05
For the set /a variant you don't need delayed expansion. set /a automatically expands variable names even without % or !. – Joey Mar 15 '10 at 3:26
@Johannes - True, I didn't know it at the time. Updated, thanks. – Carlos Gutiérrez Mar 15 '10 at 4:48
feedback

dc 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
link|improve this answer
feedback

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++;
    }
link|improve this answer
feedback

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

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
link|improve this answer
feedback

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
  }
}
link|improve this answer
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 Feb 19 '10 at 19:33
ebx is ret value in x86 – Yuval Adam Feb 19 '10 at 20:06
2  
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 Feb 19 '10 at 22:27
Can someone translate this to GCC-style assembly for the folks using Linux? – FUZxxl Sep 24 '11 at 19:26
1  
@FUZxxl: int fib(int i){int r;asm("mov $1,%%eax;mov $0,%%edx;1:add %%eax,%%edx;xchg %%eax,%%edx;loop 1b" : "=d"(r) : "c"(i) : "%eax");return r;} – Keith Randall Oct 27 '11 at 21:56
feedback

Now you procedural code monkeys have finished at your typewriters... time for some Shakespeare (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

link|improve this answer
4  
I thought you mean Shakespeare the language en.wikipedia.org/wiki/Shakespeare_%28programming_language%29 – KennyTM Feb 24 '10 at 18:27
@KennyTM: oh very droll... :-) – gbn Feb 24 '10 at 18:35
feedback

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 :)

link|improve this answer
feedback
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();
    }
}
link|improve this answer
feedback

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); 
}
link|improve this answer
feedback

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)
link|improve this answer
Equivalent to Sum[Binomial(s,k-1-s),s=0..k-1]? – Peter Taylor Mar 27 '11 at 22:04
feedback

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

link|improve this answer
feedback

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;
    }
link|improve this answer
feedback

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;
}
link|improve this answer
feedback

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
    }
}
link|improve this answer
feedback

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))]
link|improve this answer
feedback

Python generator:

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

Called n times.

link|improve this answer
feedback

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
link|improve this answer
feedback
1 2

Not the answer you're looking for? Browse other questions tagged or ask your own question.