Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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.

share|improve this question
35  
+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
11  
@ 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
10  
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
14  
@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 24 more comments

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

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

As it currently stands, this question is not a good fit for our Q&A; format. We expect answers to be supported by facts, references, or specific expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, see the FAQ for guidance.

46 Answers

1 2

JavaScript

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

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

share|improve this answer

F# Using Seq.unfold

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

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.

share|improve this answer
I like it, but KennyTM beat you to it. – SLaks Jul 7 '10 at 12:37

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

share|improve this answer

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
share|improve this answer

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

share|improve this answer

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

share|improve this answer

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, ...]

share|improve this answer

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%
share|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

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
share|improve this answer

J 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

share|improve this answer
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
share|improve this answer

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.

share|improve this answer

Python generator:

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

Called n times.

share|improve this answer

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

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

share|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

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]"""
share|improve this answer

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); 
}
share|improve this answer
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.

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

Scala:

Thanks to scalaz

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)
share|improve this answer

OpenOffice Calc / MS Excel

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

Grab handle of A3

And fill down

share|improve this answer
I like this one!!! – Yin Zhu Mar 9 '10 at 2:19
1  
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
5  
Memoization, anyone? – Matt Ball Aug 12 '10 at 15:34
Priceless :) +1 – Soner Gönül Aug 7 '11 at 14:37
This one is my favourite. :P – Joe Z. Jan 25 at 1:34

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

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(); }
}
share|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
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 :-) ).

share|improve this answer
56  
+1 for cheating – SLaks Feb 19 '10 at 13:55
18  
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
7  
what's wrong with Console.WriteLine(i++)? what a waste of lines – Nico Nov 17 '10 at 20:55
show 5 more comments

Maybe I read too literally?

std::string Fibonacci(unsigned n)
{
   return "either the nth Fibonacci number or the first n Fibonacci numbers.";
}
share|improve this answer
35  
+1 for sheer cheek – Platinum Azure Feb 20 '10 at 3:25
25  
-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

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;
}
share|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

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

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;
}
share|improve this answer
2  
+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
1 2

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