Código de Fibonacci Golf


Genere la secuencia de Fibonacci en la menor cantidad de caracteres posible. Cualquier lenguaje está bien, excepto uno que defina con un operador, f, que imprime los números de Fibonacci.

Punto de Partida: 25 14 los caracteres{[9] {} en[6]}Haskell:

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

f=0:scanl(+)1f
Author: Claudiu, 2008-10-24

30 answers

Arrepentirse, 9, 8 caracteres

1↓[2?+1]

O 10 caracteres con impresión:

1↓[2?+↓£1]

Ejecutar usando:

RePeNt "1↓[2?+1]"

RePeNt es un lenguaje de juguete basado en pila que escribí (y todavía estoy mejorando) en el que todos los operadores/funciones/bloques/bucles usan Notación Polaca Inversa (RPN).

Command      Explanation                                              Stack
-------      -----------                                              -----

1            Push a 1 onto the stack                                  1
↓            Push last stack value                                    1 1
[            Start a do-while loop                                    1 1
2?           Push a two, then pop the 2 and copy the last 2 stack     1 1 1 1
             items onto the stack
+            Add on the stack                                         1 1 2
↓£           Push last stack value then print it                      1 1 2
1            Push a 1 onto the stack                                  1 1 2 1
]            Pop value (1 in this case), if it is a 0 exit the loop   1 1 2
             otherwise go back to the loop start.

La respuesta está en la pila que se construye como: {[12]]}

1 1
1 1 2
1 1 2 3
1 1 2 3 5

Nunca termina (tiene el eqivilent de un bucle C#/JAVA do { } while(true)) porque la secuencia nunca terminará, pero un la solución de terminación se puede escribir así:

N_1↓nI{2?+}

Que es 12 caracteres.

Me pregunto si alguien alguna vez leerá esto: (

 29
Author: Callum Rogers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-13 22:30:20

18 caracteres de inglés..

"Secuencia de Fibonacci"

Ok, fallo. :)

 43
Author: Krakkos,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-24 12:03:52

13 caracteres de Golfscript:

2,~{..p@+.}do

Actualización para explicar el funcionamiento del script:

  1. 2, hace una matriz de [0 1]
  2. ~ pone esa matriz en la pila
  3. Por lo tanto, en el momento en que ejecutamos el do, comenzamos la pila con 0 1 (1 en la parte superior de la pila)

El bucle do:

  1. Cada . duplica el elemento superior de la pila; aquí, hacemos esto dos veces (dejándonos con 0 1 1 1 en la inicial run)
  2. p imprime el valor superior (dejándonos con 0 1 1)
  3. @ gira los 3 elementos superiores de la pila, de modo que el tercero superior esté en la parte superior (1 1 0)
  4. + agrega los 2 elementos principales de la pila (dejando 1 1)
  5. . duplica el valor superior, para que el bucle do pueda verificar su veracidad (para determinar si debe continuar)

Rastreando esto mentalmente un par de bucles será suficiente para decirte que esto hace lo necesario adición para generar los valores de la secuencia de Fibonacci.

Dado que GolfScript tiene bignums, nunca habrá un desbordamiento de enteros, por lo que el valor de la parte superior de la pila al final del bucle do nunca será 0. Por lo tanto, el script se ejecutará para siempre.

 33
Author: Chris Jester-Young,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-13 21:10:49

Lenguaje: Errores del compilador de C++
Personajes: 205

#define t template <int n> struct 
#define u template <> struct f
t g { int v[0]; };
t f { enum { v = f<n-1>::v + f<n-2>::v }; g<v> x;};
u<1> { enum { v = 1 }; };
u<0> { enum { v = 0 }; };
int main() { f<10> x; }
 14
Author: Eclipse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-05 02:46:06

Perl 6-22 caracteres:

sub f{1,1...{$^a+$^b}}
 14
Author: mpeters,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-11 14:01:51

X86 (C-callable) modo real, 14 bytes.
La entrada es n en la pila, devuelve F n en AX.

59 31 C0 E3 08 89 C3 40 93 01 D8 E2 FB C3
 11
Author: I. J. Kennedy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-08 22:54:05

Brainfuck , 33 caracteres:

+.>+.[<[>+>+<<-]>.[<+>-]>[<+>-]<]
 11
Author: Eric Mickelsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-25 01:31:09

22 caracteres con dc:

1[pdd5**v1++2/lxx]dsxx

Invoque con:

dc -e'1[pdd5**v1++2/lxx]dsxx'

O:

echo '1[pdd5**v1++2/lxx]dsxx' | dc

Nota: no es mi trabajo, robado de perlmonks.

 10
Author: Chris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-24 09:53:07

J, 27 caracteres para una función no recursiva:

f=:3 :'{:}.@(,+/)^:y(0 1x)'

+/ sumas sobre una lista.
(,+/) añade la suma de una lista a su cola.
}.@(,+/) suma una lista, agrega un elemento a su cola y suelta el primer elemento.
}.@(,+/)^:y itera la función anterior y veces.
}.@(,+/)^:y(0 1x) aplica la función anterior a la lista (0,1) (el x lo convierte en un entero).
{:}.@(,+/)^:y(0 1x) toma el último elemento de la lista de salida de lo anterior.
f=:3 :'{:}.@(,+/)^:y(0 1x)' define f ser una función en una variable y.

 9
Author: ephemient,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-24 18:21:02

Para que conste:

  • Lua (66 caracteres): function f(n)if n<2 then return n else return f(n-1)+f(n-2)end end
  • JavaScript (41 caracteres): function f(n){return n<2?n:f(n-1)+f(n-2)}
  • Java (41 caracteres): int f(int n){return n<2?n:f(n-1)+f(n-2);}

No soy muy adepto a los lenguajes súper concisos... :- P

Chris tiene razón, solo tomé el algoritmo simple y recursivo. En realidad, el lineal es aún más corto en Lua (gracias a la asignación múltiple)! JavaScript no es tan afortunado y Java es peor, tener que declarar vars...

  • Lua (60 caracteres): function f(n)a=1;b=0;for i=1,n do a,b=b,a+b end return b end
  • JavaScript (60 caracteres): function f(n){a=1;b=i=0;for(;i++<n;){x=a+b;a=b;b=x}return b}
  • Java (71 caracteres): int f(int n){int a=1,b=0,i=0;for(;i++<n;){int x=a+b;a=b;b=x;}return b;}

Escribiría el código de Lua con local a,b=1,0 pero es más largo, así que contaminemos _G! ;-) Idem for JS.

Para completar, aquí están las versiones recursivas de terminal. El de Lua, usando tail call, es tan rápido como el lineal (¡pero 69 caracteres, es el más largo!) - necesidad de llamar con tres parámetros, n,1,0.

  • Lua (69 char, ¡más largo!): function f(n,a,b)if n<1 then return b else return f(n-1,b,a+b)end end
  • JavaScript (44 caracteres): function f(n,a,b){return n<1?b:f(n-1,b,a+b)}
  • Java (52 caracteres): int f(int n,int a,int b){return n<1?b:f(n-1,b,a+b);}
 7
Author: PhiLho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-24 14:38:25

Corregido después de comentarios (gracias Sebastian), no era una solución de secuencia, así que aquí vamos con 42 caracteres (incluye el \n):

def f(a=0,b=1):
 while 1:yield a;a,b=b,a+b

ANTIGUO post a continuación

Python, 38 caracteres.

f=lambda n:n if n<2 else f(n-1)+f(n-2)

No tan corto, pero el más legible en mi opinión: P

EDITAR: Aquí está la forma analítica (si alguien necesita verlo en python: -)

f=lambda n:int(.5+(.5+5**.5/2)**n/5**.5)
 7
Author: Andrea Ambu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-20 23:54:10

Script por lotes para Windows XP (y versiones posteriores). Esta función por lotes cuando se le da un solo argumento - cantidad, genera cantidad + 1 números de Fibonacci y los devuelve como una cadena (EL LOTE realmente no tiene conjuntos) en la variable %r% (369 caracteres, o 347 caracteres - si eliminamos la sangría):

:f
    set i=0
    set r=1
    set n=1
    set f=0
    :l
        if %n% GTR %~1 goto e
        set f=%f% %r%
        set /A s=%i%+%r%
        set i=%r%
        set r=%s%
        set /A n+=1
        goto l
    :e
    set r=%f%
    exit /B 0

Y aquí está el script completo, para verlo en acción (simplemente cópielo en un archivo CMD o BAT y ejecútelo):

@echo off
call :ff 0
call :ff 1
call :ff 2
call :ff 3
call :ff 5
call :ff 10
call :ff 15
call :ff 20
exit /B 0

:ff
    call :f "%~1"
    echo %~1: %r%
    exit /B 0

:f
    set i=0
    set r=1
    set n=1
    set f=0
    :l
        if %n% GTR %~1 goto e
        set f=%f% %r%
        set /A s=%i%+%r%
        set i=%r%
        set r=%s%
        set /A n+=1
        goto l
    :e
    set r=%f%
    exit /B 0
 6
Author: Paulius,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-30 13:38:54

Microsoft Batch-15 caracteres

Viejo desafío, pero el mundo debe saber que es posible:

%1
%0 %1%2 %1 #

La salida es a stderr en unario, contando solo los # caracteres. Dependiendo de las restricciones de espacio del sistema anfitrión, puede producir solo los primeros 14 números aproximadamente.

 6
Author: user1469191,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-20 12:14:57

Idioma: dc, número de caracteres: 20

Solución de cc más corta.

dc -e'1df[dsa+plarlbx]dsbx'
 5
Author: Hynek -Pichi- Vychodil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-29 02:13:56

F#:

(0,1)|>Seq.unfold(fun(a,b)->Some(a,(b,a+b)))

44 Caracteres

 5
Author: leen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-11 14:39:25

Aquí está mi mejor esquema de uso, en 45 caracteres:

(let f((a 0)(b 1))(printf"~a,"b)(f b(+ a b)))
 5
Author: Henk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-07 11:37:13

MS Excel: 11 caracteres:

=SUM(A1:A2)

Escriba 1 en las 2 celdas superiores, luego coloque la fórmula anterior en la celda A3. Copia la fórmula en la hoja de cálculo.

Comienza a perder precisión debido al redondeo en coma flotante en la fila 74.
Supera 10^307 y se desborda a un error #NUM! en la fila 1477.

 4
Author: BradC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-08 16:48:30

Genere la secuencia de Fibonacci. secuencia SECUENCIA!

 3
Author: annoying kid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-24 18:32:41

C#

Estoy viendo muchas respuestas que en realidad no generan la secuencia, sino que le dan solo el número de fibonacci en la posición *n usando recursión, que cuando se loopea para generar la secuencia se vuelve cada vez más lento a valores más altos de n.

using System;
static void Main()
{
  var x = Math.Sqrt(5);
  for (int n = 0; n < 10; n++)
    Console.WriteLine((Math.Pow((1 + x) / 2, n) - Math.Pow((1 - x) / 2, n)) / p) ;
}
 3
Author: BenAlabaster,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-04 23:22:42
let rec f l a b =function 0->a::l|1->b::l|n->f (a::l) b (a+b) (n-1) in f [] 1 1;;

80 caracteres, pero realmente genera la secuencia, en tiempo lineal.

 3
Author: huitseeker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-06-30 01:21:02

Ruby (30 caracteres):

def f(n)n<2?n:f(n-1)+f(n-2)end
 3
Author: Firas Assaad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-07 11:36:08

@Andrea Ambu

Una versión iterativa de pythonic fibonacci() debería verse algo así:

def fibonacci(a=0, b=1):
    while True:
        yield b
        a, b = b, a+b
 3
Author: J.F. Sebastian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-18 04:00:35

Lua-49 caracteres

function f(n)return n<2 and n or f(n-1)+f(n-2)end
 2
Author: Nican,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-08 22:04:33

Befunge-93

31 caracteres

Generará una lista infinita de los números de Fibonacci, desde 0 hacia arriba, separados por pestañas (podría reducirse a 29 caracteres eliminando 9, en la primera fila, a expensas de que no haya espacios en blanco entre los números).

Desafortunadamente, todos los intérpretes de Befunge-93 que he probado parecen desbordarse después de 65k, por lo que la salida solo es correcta hasta e incluyendo 46368 (que es F24).

#v::1p1>01g:.\:01p+9,#
 >     ^

Confirmado para funcionar (con la advertencia anterior) con el intérprete Befunge-93 en Javascript y el Applet Visual Befunge Completo .

Estoy orgulloso de decir que este es un trabajo completamente original (es decir, no copié este código de nadie), y es mucho más corto que la solución Befunge actualmente en Código Rosetta.

 2
Author: Mark Rushakoff,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-10 19:49:26

BrainF * * k:

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

Eso generará los primeros 5. Para generar más, reemplace el 5 + al principio con más: eg:

>++++++++++++++++++++++>+>+<[[>]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[>+>+<<-]>>[<<+>>-]<[<]>-]
 2
Author: Tom H,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-14 20:24:25

No el más corto, pero el más rápido en el momento de la publicación. :-)

float f(float n) {
    return (pow(1+sqrt(5.0))/2.0),n) - pow(1+sqrt(5.0))/2.0),n)/sqrt(n));
}
 1
Author: mstrobl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-24 14:55:38

33 caracteres en C:

F(n){return n<2?n:F(n-1)+F(n-2);}
 1
Author: Adam Rosenfield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-24 18:36:06

Delphi Prism (Delphi para. net)

f:func<int32,int32>:=n->iif(n>1,f(n-1)+f(n-2),n)

49 caracteres

 1
Author: Steve,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-06 21:57:19

El ejemplo anterior de Ruby no funcionará sin punto y coma o líneas nuevas, por lo que en realidad son 32 caracteres. Este es el primer ejemplo que realmente genera la secuencia, no solo devuelve el valor de un índice especificado.

Ruby:
53 caracteres, incluidas las nuevas líneas:

def f(n);n<2?1:f(n-1)+f(n-2);end
0.upto 20 {|n|p f n}

O si desea una función que produzca una estructura de datos utilizable, 71 caracteres:

def f(n);n<2?1:f(n-1)+f(n-2);end
def s(n);(0..n).to_a.map {|n| f(n)};end

O aceptar args de línea de comandos, 70 caracteres:

def f(n);n<2?1:f(n-1)+f(n-2);end
p (0..$*[0].to_i).to_a.map {|n| f(n)}
 1
Author: Lex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-01 21:27:22

Ensamblador PDP-11 ( fuente )

    .globl  start
    .text
start:
    mov $0,(sp)
    mov $27,-(sp)
    jsr pc, lambda
print_r1:
    mov $outbyte,r3
div_loop:
    sxt r0
    div $12,r0
    add $60,r1
    movb    r1,-(r3)
    mov r0,r1
    tst r1
    jne div_loop
    mov $1,r0
    sys 4; outtext; 37
    mov $1,r0
    sys 1
lambda:
    mov 2(sp),r1
    cmp $2,r1
    beq gottwo
    bgt gotone
    sxt r0
    div $2,r0
    tst r1
    beq even
odd:
    mov 2(sp),r1
    dec r1
    sxt r0
    div $2,r0
    mov r0,-(sp)
    jsr pc,lambda
    add $2,sp
    mov r0,r3
    mov r1,r2
    mov r3,r4
    mul r2,r4
    mov r5,r1
    mov r3,r4
    add r2,r4
    mul r2,r4
    add r5,r1
    mul r3,r3
    mov r3,r0
    mul r2,r2
    add r3,r0
    rts pc
even:
    mov 2(sp),r1
    sxt r0
    div $2,r0
    dec r0
    mov r0,-(sp)
    jsr pc,lambda
    add $2,sp
    mov r0,r3
    mov r1,r2
    mov r2,r4
    mul r2,r4
    mov r5,r1
    mov r2,r4
    add r3,r4
    mul r4,r4
    add r5,r1
    mov r2,r4
    add r3,r4
    mul r2,r4
    mov r5,r0
    mul r2,r3
    add r3,r0
    rts pc
gotone:
    mov $1,r0
    mov $1,r1
    rts pc
gottwo:
    mov $1,r0
    mov $2,r1
    rts pc

    .data
outtext:
    .byte 62,63,162,144,40,106,151,142,157,156
    .byte 141,143,143,151,40,156,165,155
    .byte 142,145,162,40,151,163,40
    .byte 60,60,60,60,60
outbyte:
    .byte 12
 1
Author: JUST MY correct OPINION,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-12 15:55:45