Fibonacci-orial


36

Définition

La séquence de Fibonacci F(n), sur les entiers positifs, est définie comme telle:

1. F(1) = 1
2. F(2) = 1
3. F(n) = F(n-1) + F(n-2), where n is an integer and n > 2

Le Fibonacci-orial d'un entier positif est le produit de [F(1), F(2), ..., F(n)].

Tâche

Étant donné entier positif n, trouver le Fibonacci-orial de n.

Spécifications

Le fibronome de 100doit calculer en moins de 5 secondes sur un ordinateur raisonnable.

Testcases

n   Fibonacci-orial of n
1   1
2   1
3   2
4   6
5   30
6   240
7   3120
8   65520
9   2227680
10  122522400
11  10904493600
12  1570247078400
13  365867569267200
14  137932073613734400
15  84138564904377984000
16  83044763560621070208000
17  132622487406311849122176000
18  342696507457909818131702784000
19  1432814097681520949608649339904000
20  9692987370815489224102512784450560000
100 3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000

Les références



1
@LuisMendo La somme de fibonacci est ... vous l'avez deviné, fibonacci. Eh bien, moins un.
Leaky Nun

2
@LeakyNun Actuellement, la réponse JavaScript ne complète que 15 cas de test, car JavaScript ne peut pas correctement comparer (ou manipuler) des nombres supérieurs à 2 ^ 53 - 1. Ceci est probablement similaire pour beaucoup des soumissions présentées ici, car la plupart des langues ne le sont pas. chiffres de soutien que gros
MayorMonty

1
Qu'entendez-vous par "ordinateur raisonnable"?
Erik the Outgolfer

2
-1 parce que cela semble être plusieurs défis combinés (étendue, fibonacci de chacun, factoriel) sans raccourcis particulièrement intéressants.
Esolanging Fruit

Réponses:


63

Mathematica, 10 octets

Fibonorial

Un autre logiciel intégré Mathematica bien battu par une langue de golf sans le logiciel intégré.


49
Je… w-quoi… pourquoi, Mathematica?!
Lynn

3
Oublié que la fonction existait même!
LegionMammal978

3
@ Lynn Rule 35 : Si elle existe, elle a une fonction Mathematica;)
Beta Decay

9
@ BetaDecay Je pensais que nous avions établi qu'il s'agissait de la règle 110 .
Martin Ender

1
Non, la règle 110 est très différente. Bien que je suis sûr que Mathematica possède également une fonction intégrée pour cela.
AdmBorkBork

27

Gelée , 6 octets

+С1ḊP

L'entrée 100 se termine en 500 ms localement. Essayez-le en ligne!

Comment ça marche

+С1ḊP  Niladic link. No input.
        Since the link doesn't start with a nilad, the argument 0 is used.

   1    Yield 1.
+       Add the left and right argument.
 С     Read a number n from STDIN.
        Repeatedly call the dyadic link +, updating the right argument with
        the value of the left one, and the left one with the return value.
        Collect all values of the left argument into an array.
    Ḋ   Dequeue; discard the first Fibonacci number (0).
     P  Product; multiply the remaining ones.

Alors est +¡1un nth fibonacci non construit et +С1est le n premiers nombres de Fibonacci?
Caird coinheringaahing

@cairdcoinheringaahing Assez bien.
Dennis

Je pensais qu'il y avait une fonction intégrée de fibonacci?
MilkyWay90


16

Brainfuck, 1198 1067 817 770 741 657 611 603

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

Non compressé, avec des commentaires:

# parse input (max 255)
,[>++++++[-<-------->]<<[->++++++++++<]>>,]
>+>+>>+>+<<<<<<
[->>>
  # compute next fibonacci number
  [[-]<
    [->+<]>>
    [-<+<+>>]<
    # perform carries
    [->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<[->+<
      [->[-]>>>>>>+>+<<<<<<<<[->+<]]
    ]]]]]]]]]+>>>>>>>>
  ]<<<<<<<<
  # multiplication
  [->
    # extract next digit of F_n (most significant first)
    [-<+<<+>>>]<
    [->+<]>>>
    # move back to the end
    [<<<<<
      [->>>>>>>>+<<<<<<<<]>>>>>>>>>>>>>
    ]<<<<<<<<
    # digit wise multiplication (shifting current digit)
    [->>>
      [-<<<<<<<<+>>>>
        [->+>>+<<<]>
        [-<+>]>>>
      ]<<
      # shift previous total over one gap (in effect multiplying by 10)
      [->>>>>>>+>+<<<<<<<<]<+<<<<<<<<
    ]>>>[-]>>>>>
    # add product to total
    [[-]>
      [->+<]>
      # perform carries
      [-<+>
        [-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>[-<+>
          [->>>>>>+>+<<<<<<<<[-]]
        ]]]]]]]]>
      ]<<[<]+>>>>>>>>
    ]<<<<<<<<
    [<<<<<<<<]>>>>>
    [>>>>>>>>]+<<<<<<<<
  ]>>>>>>>>>>>
  # overwrite previous product
  [<[-]>>
    [-<<+>>]>>>>>>>
  ]<<<<<<<<
  [<<<<<<<<]>>
]>>>>>>
# output product
[>>>>>>>>]<<<<<<<<
[+++++
  [-<++++++++>]<.<<<<<<<
]

Essayez-le en ligne!

Le temps d’exécution pour n = 100 est inférieur à 1 seconde avec l’interprète en ligne (environ 0,2 seconde localement utilisant mon propre interprète). L'entrée maximale est de 255, mais l'interprète doit prendre en charge environ 54 000 cellules (l'interpréteur en ligne semble envelopper sur 64 Ko).


Changer le journal

Sauvegardé environ 130 octets avec une meilleure extraction du chiffre actuel à multiplier par, et en fusionnant ajouter et reporter en un seul passage. Cela semble aussi être un peu plus rapide.

Enregistré un autre 250 octets. J'ai réussi à réduire mon bloc-notes de multiplication de deux cellules, ce qui permet d'économiser des octets un peu partout, car je n'ai pas à changer autant de chiffres. J'ai également abandonné le report après l'avoir multiplié par un chiffre et effectuer un report complet tout en ajoutant au total cumulé.

Haché encore 50, encore une fois avec une meilleure extraction du chiffre actuel à multiplier, simplement en ne le déplaçant pas de la première itération et en partant de là où il se trouve. Quelques micro-optimisations plus bas représentent environ 10 octets.

30 autres sont partis. Marquer les chiffres déjà pris avec un 0 plutôt qu'un 1 facilite leur localisation. Cela permet également de vérifier si la boucle de multiplication est un peu plus simple.

J'ai réduit le bloc-notes d'une autre cellule, pour 80 octets supplémentaires. Pour ce faire, j'ai fusionné le marqueur du produit précédent et le total cumulé en cours, ce qui réduit les décalages entre les espaces et facilite la comptabilité.

Sauvegardé 50 autres, en éliminant une autre cellule, en réutilisant le marqueur pour les chiffres de fibonacci pour marquer également le dernier chiffre pris. J'ai également pu fusionner la boucle pour décaler les totaux précédents avec la boucle de multiplication en chiffres.

Sauvegardé 8 octets lors de l'analyse de l'entrée. Oops.


14

Python, 45 octets

a=b=o=1
exec"o*=a;a,b=b,a+b;"*input()
print o

L'entrée est prise de stdin. La sortie pour n = 100 se termine trop rapidement pour que le temps soit précis. n = 1000 prend environ 1s.

Exemple d'utilisation

$ echo 10 | python fib-orial.py
122522400

$ echo 100 | python fib-orial.py
3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000

13

Haskell 41 29 octets

1 + 11 octets enregistrés par les remarques de @ Laikoni.

f=1:scanl(+)1f
(scanl(*)1f!!)

1, fEt !!sont des jetons séparés. Les premières lignes définissent la séquence de fibonacci, la seconde est une fonction qui calcule la séquence de fibonacci-orials et renvoie le n-ème pour un n donné. Il commence à imprimer les chiffres presque immédiatement, même pour n = 1000.


1
Vous pouvez vous débarrasser de l'espace (scanl(*)1f!!).
Laikoni

2
Et il y a un générateur de fibonacci plus court ici :f=1:scanl(+)1f
Laikoni

@ Laikoni C'est incroyable, merci!
Christian Sievers

2
@WillNess Je pense que je ne suis pas seulement justifié par ce que font les autres utilisateurs, mais également par meta.codegolf.stackexchange.com/questions/2419/… et meta.codegolf.stackexchange.com/questions/9031/… (mais il existe un beaucoup plus et je n'ai pas tout lu)
Christian Sievers

1
@flawr Accepteriez-vous 42+une fonction qui ajoute 42? Vous ne devriez pas, parce que c'est juste une expression inachevée. Mais en Haskell, nous pouvons ajouter des parenthèses et obtenir la section (42+) , un moyen d’écrire la fonction \n->42+n. Ici, c'est la même chose, seulement avec !!(l'opérateur infixe binaire pour l'indexation) au lieu d' +un premier opérande plus compliqué.
Christian Sievers

11

Python 2, 39 octets

f=lambda n,a=1,b=1:n<1or a*f(n-1,b,a+b)

Testez-le sur Ideone .


Vous voudrez peut-être spécifier qu'il retourne Truedans certains cas.
Leaky Nun

5
Cela ne renverrait que Truepour l'entrée 0 , ce qui n'est pas positif.
Dennis

6

J, 17 16 octets

1 octet est joué au golf avec une solution encore meilleure par miles.

[:*/+/@(!|.)\@i.

L'idée est la même que l'originale mais au lieu de former la matrice pour opérer sur des diagonales mineures, nous formons les diagonales à la volée.


Original

Pour obtenir les premiers n fibonomiaux:

*/\(#{.+//.)!/~i.

Lecture de droite à gauche ...
Créez le tableau d’entiers consécutifs ( i.) jusqu’à celui spécifié, à partir de ce tableau, créez le tableau ( /~) de coefficients binomiaux ( !) calculé à partir de chaque paire du tableau, ce tableau est le triangle situé en haut de Pascal la fin de la première ligne et tous les éléments sous la diagonale principale sont 0, heureusement pour la mise en œuvre de !. Si vous additionnez ( +/) toutes les diagonales mineures ( /.), vous obtenez des nombres de Fibonacci, mais vous devez prendre ( {.) autant de premiers éléments du tableau résultant que la longueur ( #) de la table elle-même. Ensuite, le produit ( */) appliqué à des préfixes consécutifs ( \) du tableau aboutit à la séquence souhaitée de fibonoriales.Si vous le souhaitez, vous ne pouvez prendre que le dernier en utilisant 2 octets supplémentaires ( {:), mais j’ai pensé que les afficher tous n’était pas un péché :).
NB. the previous code block is not a J function.

   {:*/\(#{.+//.)!/~i. 10
122522400

Pour les grands nombres en J que vous utilisez xà la fin:

   {:*/\(#{.+//.)!/~i. 100x
3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225...

Le programme fonctionne à 0,11 s en moyenne .

   100 timex '{:*/\(#{.+//.)!/~i.100x'
0.112124

1
Une alternative qui est une fonction [:*/+/@(!|.)\@i.utilise 16 octets. Il forme les mêmes coefficients binomiaux le long de la table que vous générez en utilisant !/~sauf qu'il le fait en prenant les préfixes de i..
miles

4

Pyth, 13 octets

u*Gs=[sZhZ)Q1

Manifestation

Cela fait appel à une astuce intelligente, sans typographie. Cinq des caractères ( u*G ... Q1) indiquent que la sortie est le produit de nombreux nombres saisis. Le reste du code génère les nombres.

=[sZhZ)met à jour la variable Zdans la liste [s(Z), h(Z)]. Puis ssomme cette liste, à multiplier.

Zest initialement 0. s, sur ints, est la fonction identité. h, sur son, est la + 1fonction. Ainsi, à la première itération, Zdevient [0, 1]. ssur les listes est la fonction somme, comme mentionné ci-dessus. hest la fonction principale. Donc, la deuxième itération est [1, 0].

Voici une liste:

Iter  Z          Sum
0     0          Not used
1     [0, 1]     1
2     [1, 0]     1
3     [1, 1]     2
4     [2, 1]     3
5     [3, 2]     5

Ces sommes sont multipliées pour donner le résultat.


4

Mathematica 25 24 bytes

With thanks to Martin Ender.

1##&@@Fibonacci@Range@#&

1##&@@Fibonacci@Range@#&@100

Timing: 63 microseconds.

{0.000063, 
3371601853146468125386964065447576689828006172937411310662486977801540
6711385898686165008341900290675836651822917015531720110825745874313823
1009903039430687777564739516714333248356092511296002464445971530050748
1235056111434293619038347456390454209587101225261757371666449068625033
9995735521655245297254676280601708866020010771376138030271586483293355
0772869860576999281875676563330531852996518618404399969665040724619325
7877568825245646129366994079739720698147440310773871269639752334356493
6789134243905645353892122400388956268116279491329780860702550826683922
9003714114129148483959669418215206272639036409444764264391237153249138
8089634845995941928089653751672688740718152064107169357399466473375804
9722605947689699525073466941890502338235963164675705844341280523988912
2373033501909297493561702963891935828612435071136036127915741683742890
4150054292406756317837582840596331363581207781793070936765786629772999
8328572573496960944166162599743042087569978353607028409125185326833249
36435856348020736000000000000000000000000}

Alternately, with same byte count: 1##&@@Fibonacci~Array~#&
Greg Martin

4

Jelly, 8 bytes

RḶUc$S€P

My first submission in Jelly. It's not as short as @Dennis' answer, but its only 2 bytes longer with a different method.

Locally, it requires about 400ms compared to 380ms with @Dennis' version for n = 100.

Try it online!

Explanation

RḶUc$S€P  Input: n
R         Generate the range [1, 2, ..., n]
          For each value x in that range
 Ḷ          Create another range [0, 1, ..., x-1]
  U         Reverse that list
   c        Compute the binomial coefficients between each pair of values
    $       Bind the last two links (Uc) as a monad
     S€   Sum each list of binomial coefficients
          This will give the first n Fibonacci numbers
       P  Take the product of those to compute the nth Fibonacci-orial

3

PARI/GP, 29 bytes

f=n->prod(i=1,n,fibonacci(i))

Or alternatively:

f=n->prod(i=a=!b=0,n,b=a+a=b)

3

R, 99 96 78 76 66 bytes

This answer is uses Binet's Formula, as well as the prod(x)function. Since R doesn't have a build-in Phi value, I defined it myself :

p=(1+sqrt(5))/2;x=1;for(n in 1:scan())x=x*(p^n-(-1/p)^n)/sqrt(5);x

It works under 5 seconds, but R tends to give Inf as an answer for those big numbers...

Ungolfed :

r=sqrt(5)
p=(1+r)/2 
x=1
for(n in 1:scan())        
    x=x*(p^n-(-1/p)^n)/r    
x

-2 bytes thanks to @Cyoce !
Oh, do I love this site ! -10 bytes thanks to @user5957401


Might be able to save a bit by storing sqrt(5) to a variable
Cyoce

since you only use N once, you can just call scan inside the 1:N bit. i.e. for(n in 1:scan()). You can also save a few characters by just using * instead of the prod() function in your for loop. Your for loop is only one line, so you don't need the curly braces either.
user5957401

Nice idea to use Binet's formula. In your spirit but only 53 bytes is function(n,N=1:n,p=5^.5)prod(((1+p)^N-(1-p)^N)/2^N/p)
Michael M

3

R, 82, 53, 49 bytes (48 bytes w/ different input style)

b=d=1;a=0;for(i in 1:scan()){d=d*b;b=a+b;a=b-a};d

If we can just precede the code with the input number, we get the 48 byte

->n;b=d=1;a=0;for(i in 1:n){d=d*b;b=a+b;a=b-a};d

EDIT: New code. Original is below:

a=function(n)ifelse(n<3,1,{v=c(1,1,3:n);for(i in 3:n)v[i]=v[i-1]+v[i-2];prod(v)})

Won't return anything other than Inf for a(100) though. And it won't work for anything but non-negative integers.

Ungolfed:

a=function(n){
   if(n<3) return(1)
   v=c(1,1,3:n)
   for(i in 3:n)
       v[i]=v[i-1]+v[i-2]
   prod(v)
}

3

Java, 165 bytes

Golfed:

BigInteger f(int n){BigInteger[]a={BigInteger.ZERO,BigInteger.ONE,BigInteger.ONE};for(int i=0;i<n;){a[++i%2]=a[0].add(a[1]);a[2]=a[2].multiply(a[i%2]);}return a[2];}

This is yet another case where BigInteger being required due to large numbers. However, I was able to keep the text BigInteger to a minimum, keeping the size down. I also compared with static imports, and it made the total length longer.

This program works by tracking three numbers in an array. The first two are the previous two Fibonacci numbers. The third is the accumulated value. The loop starts out by calculating the next value and storing it in alternating (0, 1, 0, 1, ...) array indices. This avoids needing to shift values with costly (in terms of source size) assignment operations. Then grab that new value and multiply it into the accumulator.

By avoiding temporary objects and limiting the loop to two assignment operators, I was able to squeeze out quite a few bytes.

Ungolfed:

import java.math.BigInteger;

public class Fibonacci_orial {

  public static void main(String[] args) {
    // @formatter:off
    String[][] testData = new String[][] {
      { "1", "1" },
      { "2", "1" },
      { "3", "2" },
      { "4", "6" },
      { "5", "30" },
      { "6", "240" },
      { "7", "3120" },
      { "8", "65520" },
      { "9", "2227680" },
      { "10", "122522400" },
      { "11", "10904493600" },
      { "12", "1570247078400" },
      { "13", "365867569267200" },
      { "14", "137932073613734400" },
      { "15", "84138564904377984000" },
      { "16", "83044763560621070208000" },
      { "17", "132622487406311849122176000" },
      { "18", "342696507457909818131702784000" },
      { "19", "1432814097681520949608649339904000" },
      { "20", "9692987370815489224102512784450560000" },
      { "100", "3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000" }
    };
    // @formatter:on

    for (String[] data : testData) {
      System.out.println("Input: " + data[0]);
      System.out.println("Expected: " + data[1]);
      System.out.print("Actual:   ");
      System.out.println(new Fibonacci_orial().f(Integer.parseInt(data[0])));
      System.out.println();
    }
  }

  // Begin golf
  BigInteger f(int n) {
    BigInteger[] a = { BigInteger.ZERO, BigInteger.ONE, BigInteger.ONE };
    for (int i = 0; i < n;) {
      a[++i % 2] = a[0].add(a[1]);
      a[2] = a[2].multiply(a[i % 2]);
    }
    return a[2];
  }
  // End golf

}

Program output:

Input: 1
Expected: 1
Actual:   1

Input: 2
Expected: 1
Actual:   1

Input: 3
Expected: 2
Actual:   2

Input: 4
Expected: 6
Actual:   6

Input: 5
Expected: 30
Actual:   30

Input: 6
Expected: 240
Actual:   240

Input: 7
Expected: 3120
Actual:   3120

Input: 8
Expected: 65520
Actual:   65520

Input: 9
Expected: 2227680
Actual:   2227680

Input: 10
Expected: 122522400
Actual:   122522400

Input: 11
Expected: 10904493600
Actual:   10904493600

Input: 12
Expected: 1570247078400
Actual:   1570247078400

Input: 13
Expected: 365867569267200
Actual:   365867569267200

Input: 14
Expected: 137932073613734400
Actual:   137932073613734400

Input: 15
Expected: 84138564904377984000
Actual:   84138564904377984000

Input: 16
Expected: 83044763560621070208000
Actual:   83044763560621070208000

Input: 17
Expected: 132622487406311849122176000
Actual:   132622487406311849122176000

Input: 18
Expected: 342696507457909818131702784000
Actual:   342696507457909818131702784000

Input: 19
Expected: 1432814097681520949608649339904000
Actual:   1432814097681520949608649339904000

Input: 20
Expected: 9692987370815489224102512784450560000
Actual:   9692987370815489224102512784450560000

Input: 100
Expected: 3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000
Actual:   3371601853146468125386964065447576689828006172937411310662486977801540671138589868616500834190029067583665182291701553172011082574587431382310099030394306877775647395167143332483560925112960024644459715300507481235056111434293619038347456390454209587101225261757371666449068625033999573552165524529725467628060170886602001077137613803027158648329335507728698605769992818756765633305318529965186184043999696650407246193257877568825245646129366994079739720698147440310773871269639752334356493678913424390564535389212240038895626811627949132978086070255082668392290037141141291484839596694182152062726390364094447642643912371532491388089634845995941928089653751672688740718152064107169357399466473375804972260594768969952507346694189050233823596316467570584434128052398891223730335019092974935617029638919358286124350711360361279157416837428904150054292406756317837582840596331363581207781793070936765786629772999832857257349696094416616259974304208756997835360702840912518532683324936435856348020736000000000000000000000000


2

Ruby, 39 bytes

->n{f=i=b=1;n.times{f,i,b=i,f+i,b*f};b}

36: ->n{f=i=b=1;n.times{b*=f;i=f+f=i};b}
G B

2

Javascript (ES6), 51 39 bytes

Recursive implementation (39 bytes)

f=(n,a=p=i=b=1)=>++i<n?f(n,b,p*=b+=a):p

Original implementation (51 bytes)

n=>{for(i=a=b=p=1;++i<n;){c=a;a=b;p*=b+=c}return p}

Note: Starts rounding errors for the Fibonacci-orial of 16, 100 is just Infinity, runs in what appears to be <1 second.


I made an alternate 53-byte version n=>[...Array(n)].reduce(p=>(c=a,a=b,p*=b+=c),a=1,b=0) only to discover that you'd counted the f= which isn't required saving you 2 bytes.
Neil

Fair point. My rationale was so it was callable and reusable rather than just callable.
Pandacoder

Sure, but if someone does want to reuse it then they still have the option of naming it.
Neil

@Neil Well now I went and re-implemented it and now the f= is mandatory or else it can't actually execute. :D
Pandacoder

Well at least you fixed the byte count for the original implementation.
Neil

2

DC (GNU or OpenBSD flavour), 36 bytes

File A003266-v2.dc:

0sA1sB1?[1-d0<LrlBdlA+sBdsA*r]dsLxrp

(no trailing newline)

...now the result is held on the stack instead of using a named register (is Y in version 1). The r command is not available in the original dc (see RosettaCode's Dc page).

Run:

$ time dc -f A003266-v2.dc <<< 100
337160185314646812538696406544757668982800617293741131066248697780154\
067113858986861650083419002906758366518229170155317201108257458743138\
231009903039430687777564739516714333248356092511296002464445971530050\
748123505611143429361903834745639045420958710122526175737166644906862\
503399957355216552452972546762806017088660200107713761380302715864832\
933550772869860576999281875676563330531852996518618404399969665040724\
619325787756882524564612936699407973972069814744031077387126963975233\
435649367891342439056453538921224003889562681162794913297808607025508\
266839229003714114129148483959669418215206272639036409444764264391237\
153249138808963484599594192808965375167268874071815206410716935739946\
647337580497226059476896995250734669418905023382359631646757058443412\
805239889122373033501909297493561702963891935828612435071136036127915\
741683742890415005429240675631783758284059633136358120778179307093676\
578662977299983285725734969609441661625997430420875699783536070284091\
2518532683324936435856348020736000000000000000000000000

real    0m0.005s
user    0m0.004s
sys     0m0.000s

Trying to explain:

tos is the contents of the top of the stack without removing it.
nos is the element below tos.

0 sA # push(0) ; A=pop()
1 sB # push(1) ; B=pop()
1    # push(1)
     # this stack position will incrementally hold the product
?    # push( get user input and evaluate it )
[    # start string
 1-  # push(pop()-1)
 d   # push(tos)
 0   # push(0)
 <L  # if pop() < pop() then evaluate contents of register L
 r   # exchange tos and nos
     # now nos is the loop counter
     # and tos is the bucket for the product of the fibonacci numbers
 lB  # push(B)
 d   # push(tos)
 lA  # push(A)
 +   # push(pop()+pop())
     # now tos is A+B, nos still is B 
 sB  # B=pop()
     # completes B=A+B
 d   # push(tos)
 sA  # A=pop()
     # completes B=A
     # tos (duplicated new A from above) is the next fibonacci number
 *   # push(nos*tos)
     # tos now is the product of all fibonacci numbers calculated so far
 r   # exchange tos and nos
     # now tos is the loop counter, nos is the product bucket
]    # end string and push it
d    # push(tos)
sL   # L=pop()
x    # evaluate(pop())
r    # exchange tos and nos
     # nos now is the former loop counter
     # tos now is the complete product. \o/
p    # print(tos)
     # this does not pop() but who cares? :-P

DC, 41 bytes

...straight forward, no tricks:

File A003266-v1.dc:

0sA1sB1sY?[1-d0<LlBdlA+sBdsAlY*sY]dsLxlYp

(no trailing newline)

Run:

$ for i in $(seq 4) ; do dc -f A003266-v1.dc <<< $i ; done
1
1
2
6
$ time dc -f A003266-v1.dc <<< 100
337160185314646812538696406544757668982800617293741131066248697780154\
067113858986861650083419002906758366518229170155317201108257458743138\
231009903039430687777564739516714333248356092511296002464445971530050\
748123505611143429361903834745639045420958710122526175737166644906862\
503399957355216552452972546762806017088660200107713761380302715864832\
933550772869860576999281875676563330531852996518618404399969665040724\
619325787756882524564612936699407973972069814744031077387126963975233\
435649367891342439056453538921224003889562681162794913297808607025508\
266839229003714114129148483959669418215206272639036409444764264391237\
153249138808963484599594192808965375167268874071815206410716935739946\
647337580497226059476896995250734669418905023382359631646757058443412\
805239889122373033501909297493561702963891935828612435071136036127915\
741683742890415005429240675631783758284059633136358120778179307093676\
578662977299983285725734969609441661625997430420875699783536070284091\
2518532683324936435856348020736000000000000000000000000

real    0m0.006s
user    0m0.004s
sys     0m0.004s

1
*sigh!* ... writing dc code definitely is easier than explaining it...

1
Yeah, we really need an IDE with some kind of crazy multiple-stack visualisation gadget... that would be sweet.
Joe

1
I have several ideas what to add as new commands, but the idea with the highest impact seems to be: Add a "change default stack" command. ;-)

2
...or swap default stack with a named register. That would make more knots in users' brains but would not need the default stack to have a name... ]:-)

1
Yes, that would definitely be handy! I'd also like to clear a single item, rotate items that aren't at the top of the stack, and maybe shift the top n items to another stack at once. For now, though, I still don't know how to compile dc from source. :/
Joe

2

C# 110 109 107 103 101 94 Bytes

using i=System.Numerics.BigInteger;i f(i n){i a=0,b=1,x=1;for(;n-->0;)x*=a=(b+=a)-a;return x;}

Explanation

//Aliasing BigInteger saves a few bytes
using i=System.Numerics.BigInteger;

//Since BigInteger has an implicit from int we can also change the input
//and save two more bytes.
i f(i n)
{
    //using an alternative iterative algorithm (link to source below) to cut out the temp variable
    //b is next iteration, a is current iteration, and x is the running product
    i a = 0, b = 1, x = 1; 

    //post decrement n down to zero instead of creating a loop variable
    for (; n-- > 0;)

        //The bracket portion sets the next iteration             
        //get the current iteration and update our running product
        x *= a = (b += a) - a;

    return x;
}

Iterative Fib algorithm


Given this performed so much better than I had expected I wanted to find the max N that would return in under 5 seconds, I came out with 1540 which gives a number that is 247441 digits long.
JustinM - Reinstate Monica

Impressive. How long does 1541 take to calculate, out of curiosity?
Pandacoder

@Pandacoder So with the recent change to the algorithm it has gotten significantly faster. 1541 in 755 ms so i'm going to find the new sub 5 max now.
JustinM - Reinstate Monica

@Pandacoder so the run time is varying by a fair bit ~100ms but 2565 seems to average about 5 seconds
JustinM - Reinstate Monica

How long is the number for that?
Pandacoder

2

Brain-Flak, 54 bytes

([{}]<(())>){(({})()<{({}()<([({})]({}{}))>)}{}{}>)}{}

Try it online!

Multiplication in Brain-Flak takes a long time for large inputs. Just multiplying F100 by F99 with a generic multiplication algorithm would take billions of years.

Fortunately, there's a faster way. A generalized Fibonacci sequence starting with (k, 0) will generate the same terms as the usual sequence, multiplied by k. Using this observation, Brain-Flak can multiply by a Fibonacci number just as easily as it can generate Fibonacci numbers.

If the stack consists of -n followed by two numbers, {({}()<([({})]({}{}))>)}{}{} will computen iterations of the generalized Fibonacci sequence and discard all by the last. The rest of the program just sets up the initial 1 and loops through this for all numbers in the range n...1.

Here's the same algorithm in the other languages provided by this interpreter:

Brain-Flak Classic, 52 bytes

({}<(())>){(({})[]<{({}[]<(({}<>)<>{}<>)>)}{}{}>)}{}

Try it online!

Brain-Flueue, 58 bytes

<>(<(())>)<>{(({}<>)<{({}({}))({}[()])}{}>[()]<>)}<>({}){}

Try it online!

Mini-Flak, 62 bytes

([{}()](())){(({})()({({}()([({})]({}{}))[({})])}{}{})[{}])}{}

Try it online!


1

Mathematica - 32 26 bytes

Fibonacci@i~Product~{i,#}&

@MartinEnder chopped 6 bytes!



1

Ruby, 85 Bytes

g =->x{(1..x).to_a.collect{|y|(0..y).inject([1,0]){|(a,b),_|[b, a+b]}[0]}.inject(:*)}

Turned out fine, but there's probably a shorter solution.

Fast Fibonnaci calculation taken from here: link

Test it here


1

Julia, 36 bytes

!x=[([1 1;1 0]^n)[2]for n=1:x]|>prod

1

Brain-Flak, 110 104 100 bytes

Try it online!

({}<((())<>)>){({}[()]<<>(({})<>({}<>)<>)>)}<>{}([[]]()){({}()<({}<>)<>({<({}[()])><>({})<>}{})>)}{}

Explanation

First we run an improved version of the Fibonacci sequence generator curtesy of Dr Green Eggs and Iron Man

({}<((())<>)>){({}[()]<<>(({})<>({}<>)<>)>)}<>{}

Then while the stack has more than one item on it

([[]]()){({}()<...>)}

multiply the top two items

({}<>)<>({<({}[()])><>({})<>}{})

and pop the extra zero

{}

1
Unfortunately, I think this is invalid since it takes over 10 seconds for an input of 25. The algorithm is very inefficient (just like the language is), so calculating it for 100 would probably take hours.
DJMcMayhem

1

Clojure, 70 bytes

Clojure isn't really a good language for code golf. Oh well.

Try it at http://tryclj.com.

(last(nth(iterate(fn[[a b r]][b(+ a b)(* r(+ a b))])[0N 1 1])(dec n)))

1

Forth, 55 bytes

Uses an iterative approach, built upon my Fibonacci answer in Forth. The results overflow arithmetically for n > 10. The answer is case-insensitive.

: f >r 1 1 r@ 0 DO 2dup + LOOP 2drop 1 r> 0 DO * LOOP ;

Try it online



1

JavaScript (ES6), 46 bytes

f=(n,a=1,b=1,c=i=1)=>n==i?c:f(n,b,a+b,c*b,++i)

Uses recursion and accumulator variables. Rounding errors start at f(16).

En utilisant notre site, vous reconnaissez avoir lu et compris notre politique liée aux cookies et notre politique de confidentialité.
Licensed under cc by-sa 3.0 with attribution required.