| Bytes | Lang | Time | Link |
|---|---|---|---|
| 004 | Nekomata + n | 230226T133012Z | alephalp |
| 033 | Python 3.8 | 250517T191010Z | 8051Enth |
| 028 | h6 | 250412T184023Z | noodle p |
| nan | 250125T141858Z | RARE Kpo | |
| 009 | ☾ | 250319T222630Z | Joao-3 |
| 060 | SAKO | 250319T175714Z | Acrimori |
| 016 | APLNARS | 250112T151330Z | Rosario |
| 012 | TinyAPL | 250313T193357Z | noodle p |
| 007 | Uiua | 240402T222707Z | noodle p |
| 014 | TinyAPL | 250313T165858Z | RubenVer |
| 011 | Jalapeño | 250212T030101Z | ATaco |
| 041 | Periodically | 250207T194253Z | madeforl |
| 110 | TSQL | 250206T211402Z | CrSb0001 |
| 030 | Hatchback | 241211T175457Z | madeforl |
| 030 | Javascript | 250117T011131Z | Dominik |
| 118 | Bespoke | 250115T204810Z | Josiah W |
| 005 | Vyxal 3.5 | 250112T200430Z | Ginger |
| 155 | jbasher2 | 241212T163209Z | madeforl |
| 022 | Raku Perl 6 rakudo | 241211T172223Z | xrs |
| 025 | punchcode | 241210T165048Z | madeforl |
| 108 | Python 3.8 prerelease | 210729T173413Z | aeh5040 |
| 038 | AWK | 240524T200604Z | C K |
| 097 | TypeScript’s type system | 231225T160723Z | noodle p |
| 013 | Labyrinth | 240208T001341Z | Bubbler |
| 014 | Trilangle | 230301T221934Z | Bbrk24 |
| 031 | Swift | 231231T195638Z | macOSist |
| 036 | Python 3.8 | 231211T182343Z | mbomb007 |
| 012 | Uiua | 230927T144721Z | ed Z |
| 194 | ELF executable x64 | 230910T155407Z | bsoelch |
| 026 | Headass | 230910T002607Z | thejonym |
| 1717 | Dyalog APL | 230830T124809Z | greta_sa |
| 006 | Itr | 230805T150606Z | bsoelch |
| 011 | ForWhile | 230805T113231Z | bsoelch |
| 011 | Desmos | 230503T195925Z | Jakdad J |
| 041 | Desmos | 230503T141258Z | Not A Ch |
| 002 | Thunno 2 | 230429T163846Z | The Thon |
| nan | 230102T114830Z | The Thon | |
| 009 | Brachylog | 190827T071739Z | Unrelate |
| 009 | Rattle | 220218T173735Z | d01 |
| 011 | Haskell + hgl | 230111T225922Z | Wheat Wi |
| 4502 | Seed | 220317T191444Z | autumn |
| 039 | Befunge98 PyFunge | 230102T032425Z | autumn |
| 050 | Excel | 221129T152358Z | Engineer |
| 008 | Juby | 221122T222501Z | Jordan |
| 459 | Nibbles | 221116T115451Z | Dominic |
| 043 | C | 221109T205805Z | madex |
| 033 | Python | 160814T071623Z | piRSquar |
| 024 | Ruby | 110128T075156Z | st0le |
| 008 | K | 221025T232431Z | d-static |
| 055 | Go | 221013T153558Z | bigyihsu |
| 010 | HOPS | 220610T020023Z | alephalp |
| nan | Fig | 220622T200445Z | Seggan |
| 016 | APLDyalog Unicode | 220921T062358Z | thejonym |
| 014 | ShapeScript | 151115T151654Z | Dennis |
| 006 | Hexagony | 151103T130435Z | alephalp |
| 012 | Stackish | 161121T202249Z | ender_sc |
| 002 | Husk | 170802T022811Z | ბიმო |
| 024 | JavaScript ES6 24 Characters | 140331T204338Z | MT0 |
| 298 | SunSip w n | 220829T023900Z | Number B |
| 032 | Perl 5 | 210411T022911Z | Deadcode |
| 008 | Regex 🐇 ECMAScriptRME / Perl / PCRE / Raku | 220720T230516Z | Deadcode |
| 135 | Trianguish | 220729T171505Z | rydwolf |
| 012 | RASEL | 220721T193226Z | Nakilon |
| 031 | Desmos | 220721T091404Z | MathEnth |
| 004 | Chocolate | 220628T230657Z | naffetS |
| 019 | Regenerate | 220714T192109Z | Deadcode |
| 022 | Cubestack | 220630T082206Z | tybocopp |
| 001 | MathGolf | 220610T031741Z | naffetS |
| 023 | R | 220602T135337Z | Giuseppe |
| 038 | GeoGebra | 220527T072750Z | Aiden Ch |
| 028 | rSNBATWPL | 220525T023016Z | naffetS |
| 003 | Factor + benchmark.fib3 | 220521T080754Z | chunes |
| 045 | BitCycle u | 220511T021659Z | emanresu |
| 038 | Nim | 210628T221152Z | Qaziquza |
| 048 | Nim | 220418T155008Z | Qaziquza |
| 003 | flax | 220220T044943Z | zoomlogo |
| 262 | LOLCODE | 220406T225731Z | naffetS |
| 033 | Quipu | 211120T095112Z | alephalp |
| 058 | PHP 4 | 220401T060744Z | user1117 |
| 045 | Mascarpone | 220216T205956Z | user1011 |
| 036 | Lua | 220228T203153Z | SilverPh |
| 055 | Halfwit | 220220T093622Z | emanresu |
| 186 | TypeScript's type system | 211003T083858Z | ruohola |
| nan | Hexagony 61 bytes | 220108T142450Z | TJC Game |
| 013 | BQN | 211228T170028Z | Dominic |
| 044 | Python 3 | 211006T051020Z | Stephen |
| 028 | jq n | 210907T132629Z | ovs |
| 016 | Grok | 210730T173714Z | Aaroneou |
| 002 | Vyxal | 210408T122634Z | lyxal |
| 019 | Knight | 210522T031052Z | EasyasPi |
| 036 | Red | 210606T013346Z | dingledo |
| 046 | C clang | 210602T100259Z | Stack Ex |
| 047 | Red | 210605T045428Z | Razetime |
| 170 | COBOL GNU | 210529T050807Z | dingledo |
| 022 | Brainfuck | 110128T022626Z | R. Marti |
| 014 | Haskell | 110128T015632Z | Anon. |
| 035 | Pinecone | 210421T160554Z | wasif |
| 018 | Branch | 210417T174632Z | hyperneu |
| 005 | Duocentehexaquinquagesimal | 210416T210747Z | Makonede |
| 026 | Barrel | 210414T003329Z | LorenDB |
| 007 | APL Dyalog Unicode | 210410T182053Z | Andrew O |
| 032 | V vim | 210410T072659Z | Razetime |
| 041 | VBScript | 210410T062846Z | wasif |
| nan | Pxem | 210408T114521Z | user1004 |
| 035 | Whispers v3 | 210219T172406Z | OldSandb |
| 015 | ><> | 110331T185726Z | Kevin Br |
| 013 | BRASCA | 210122T092747Z | SjoerdPe |
| 008 | convey | 201206T161156Z | xash |
| 023 | Javascript | 130318T045811Z | lmcanava |
| 015 | x86 machine code | 200912T072703Z | Febriyan |
| 082 | Rockstar | 200910T115737Z | Shaggy |
| 005 | Arn | 200815T050237Z | ZippyMag |
| 046 | Flurry | 200811T091919Z | Bubbler |
| 054 | Flurry | 200810T224750Z | Esolangi |
| 033 | Javascript | 200714T231151Z | Maciej S |
| 068 | GAS x8664 for Linux Machine code | 200711T083345Z | General |
| 013 | Intel 8087 FPU | 190110T215104Z | 640KB |
| 032 | R | 160812T144634Z | user5957 |
| nan | Python 2 | 200710T084037Z | math sca |
| 016 | Actually | 200710T090728Z | PkmnQ |
| 028 | International Phonetic Esoteric Language | 200609T183859Z | bigyihsu |
| 017 | dc | 200316T052940Z | Mitchell |
| 106 | Go | 200421T014943Z | martin |
| 027 | Ral | 200417T204433Z | Endenite |
| 013 | Pyth | 200402T094606Z | Mukundan |
| 036 | Erlang escript | 200316T013530Z | user9206 |
| 079 | JVM Byte Code | 200115T014900Z | ankh-mor |
| 087 | Taktentus | 191231T161247Z | 0x3 |
| 006 | tq | 191231T151416Z | user8505 |
| 057 | C gcc | 191020T201938Z | Duarte A |
| 007 | Gol><> | 190926T182932Z | KrystosT |
| 090 | Java | 161006T113427Z | Fabian R |
| 025 | Cascade | 190925T044052Z | Jo King |
| 002 | Oasis | 190907T142308Z | user8505 |
| 032 | BrainFlak | 171026T100302Z | 0 |
| 031 | Zsh | 190828T043301Z | roblogic |
| 008 | 8086/8088 machine code | 190830T172703Z | Sophie S |
| 043 | pure bash | 190829T223000Z | F. Hauri |
| 019 | Flobnar | 180814T050009Z | Jo King |
| 042 | Golfscript | 190828T211225Z | wade kin |
| 120 | Jasmin | 190827T133119Z | ankh-mor |
| nan | bash pur | 110404T150416Z | user unk |
| 007 | 33 | 190828T092342Z | TheOnlyM |
| 484 | x86 Machine Code ELF format | 190827T074012Z | Kamila S |
| 010 | Keg | 190810T102157Z | Edgex42 |
| 016 | BitCycle | 190329T113008Z | Jo King |
| 385 | Pyramid Scheme | 190726T021617Z | Khuldrae |
| 009 | \/\/> | 190712T052403Z | Jo King |
| 010 | Ouroboros | 161018T230417Z | DLosc |
| 037 | Python 3 | 190131T222757Z | Martmist |
| 021 | BitCycle | 190329T070141Z | DLosc |
| 035 | Awk | 190226T164508Z | James Br |
| 087 | Alchemist | 181125T175804Z | ბიმო |
| 1413 | Brainfuck | 141217T161759Z | Stefnotc |
| 068 | Alchemist | 190201T070519Z | Jo King |
| 042 | C++ | 190130T174836Z | juh |
| 056 | C# .NET Core | 190111T220011Z | Destroig |
| 031 | Symbolic Python | 181217T025858Z | Jo King |
| 037 | R | 181218T131842Z | J.Doe |
| 066 | Pure | 181218T125005Z | J. Sall& |
| 043 | Python 3 | 181217T194014Z | CodeGolf |
| 027 | Tcl | 170708T213834Z | sergiol |
| 045 | Little Man Computer | 181216T114944Z | FlipTack |
| 008 | Burlesque | 151022T170034Z | mroman |
| 009 | Pip | 151103T071053Z | DLosc |
| 029 | Prolog | 181104T075143Z | Alex Tro |
| 100 | Rust | 180923T140353Z | T_human |
| 070 | Pascal FPC | 180819T001147Z | AlexRace |
| 019 | Alumin | 180818T235201Z | Conor O& |
| 015 | Tidy | 180818T233403Z | Conor O& |
| 002 | 05AB1E | 180816T200319Z | Mr. Xcod |
| 015 | AsciiDots | 180803T140553Z | Alion |
| 015 | Ahead | 180815T065205Z | snail_ |
| nan | BinaryEncoded Golfical | 151217T121950Z | SuperJed |
| 3033 | Haskell | 180809T192538Z | mrFooble |
| 014 | x86 assembly 32bit | 180810T011051Z | Obsequio |
| 019 | Julia 0.6 | 180809T191356Z | Muhammad |
| 016 | µ6 | 180805T235025Z | ბიმო |
| 031 | Python 2 | 180803T144717Z | Triggern |
| 057 | Javascript | 180531T204251Z | 77Tigers |
| 023 | Retina 0.8.2 | 180413T093526Z | Neil |
| 074 | Add++ | 180128T011908Z | caird co |
| 035 | Lean | 180331T003244Z | Leaky Nu |
| 049 | Elixir | 180327T174109Z | Okx |
| 036 | R16K1S60 Assembly | 180320T172102Z | moonhear |
| 028 | SmileBASIC | 180320T160202Z | 12Me21 |
| 026 | Dodos | 180315T035942Z | Dennis |
| 002 | Stax | 180315T014039Z | Weijun Z |
| 047 | Whitespace | 131202T133906Z | r.e.s. |
| 093 | Reflections | 180314T160045Z | wastl |
| 015 | Forked | 180212T175151Z | MD XF |
| 028 | Momema | 180212T192641Z | Esolangi |
| 028 | Coconut | 180210T132407Z | ovs |
| 011 | ><> | 180201T003457Z | Jo King |
| 003 | Japt | 180131T155918Z | Shaggy |
| 013 | FALSE | 180131T143755Z | 12Me21 |
| 038 | Common Lisp | 170619T065359Z | Renzo |
| 032 | QBasic | 180125T050022Z | DLosc |
| 040 | tinylisp | 170202T185801Z | DLosc |
| 001 | Pyt | 171227T201600Z | mudkip20 |
| 012 | ><> | 171118T064317Z | Bolce Bu |
| 011 | Implicit | 170912T035151Z | MD XF |
| 064 | C | 170912T040207Z | MD XF |
| 030 | Pug | 171008T172537Z | Matheus |
| 028 | VBA | 171008T160612Z | Taylor R |
| 006 | Juby | 170215T194059Z | Cyoce |
| nan | Cy | 160325T012008Z | Cyoce |
| 036 | Chip8 | 171007T183418Z | 12Me21 |
| 016 | Recursiva | 170906T100047Z | 0xffcour |
| 035 | Axiom | 170422T065559Z | user5898 |
| 013 | Pylons | 160204T210230Z | Morgan T |
| 017 | Piet | 170826T225210Z | Josiah W |
| 007 | 05AB1E | 160705T111621Z | Vimlesh |
| 003 | Jelly | 151217T031125Z | Dennis |
| 107 | Tampio | 170826T111422Z | fergusq |
| nan | Klein | 170516T194622Z | Wheat Wi |
| 1211 | Element | 150415T220224Z | PhiNotPi |
| 227 | C | 160107T111328Z | x13 |
| 039 | PHP | 170813T184511Z | WebSmith |
| 024 | Proton | 170812T215109Z | hyperneu |
| 036 | Forth | 170804T184813Z | SydB |
| 040 | Python 2 | 170721T140657Z | SydB |
| 100 | Emojicode | 170730T015940Z | betseg |
| 034 | Python 2 | 110129T222234Z | jtjacque |
| 028 | Joy | 170722T063810Z | alephalp |
| 006 | Gaia | 170720T141435Z | Business |
| 050 | ReRegex | 170710T031748Z | ATaco |
| 030 | Python 2 | 170709T014914Z | totallyh |
| 006 | cQuents | 170625T031145Z | Stephen |
| 045 | Joy | 170619T064213Z | Laikoni |
| 055 | Java | 110908T134926Z | Dr. Hans |
| 023 | Braingolf | 170606T212547Z | totallyh |
| 046 | OIL | 170504T171827Z | Laura Bo |
| 864 | Taxi | 170504T151305Z | Engineer |
| 113 | Axiom | 170422T065510Z | user5898 |
| nan | 170421T111022Z | Shaggy | |
| 011 | Alice | 170413T181304Z | Martin E |
| 021 | bc | 170406T183801Z | Digital |
| 028 | Javascript | 170325T191217Z | Spydercr |
| 026 | Mathematica | 170324T002243Z | numberma |
| 033 | C | 170322T172507Z | Bijan |
| 027 | Forth | 151014T210553Z | mbomb007 |
| 031 | Ruby as function | 161216T130744Z | G B |
| 012 | Cylon NonCompeting | 161207T222548Z | tkaden4 |
| 075 | Python | 161117T132816Z | Juntos |
| 008 | Detour noncompeting | 160120T222424Z | Cyoce |
| 113 | Prismatic | 161114T235604Z | ender_sc |
| 029 | Java 8 | 161106T080253Z | BananyaD |
| nan | 160912T044001Z | XiKuuKy | |
| 010 | Cubix | 160317T224843Z | MickyT |
| nan | Hexagony | 151127T222857Z | FryAmThe |
| 071 | Java | 160812T150014Z | ProTheJo |
| 030 | Cy | 160325T004602Z | Cyoce |
| 011 | Sesos | 160724T004817Z | Leaky Nu |
| 023 | Perl 5 | 160224T152900Z | msh210 |
| 009 | J | 160731T181923Z | miles |
| 027 | Maple | 160725T171452Z | DSkoog |
| 020 | Julia | 160531T224742Z | Dennis |
| 020 | Detour | 160127T211625Z | Cyoce |
| 051 | C# | 130408T144137Z | Andrew G |
| 007 | PlatyPar | 160122T225002Z | Cyoce |
| 043 | Python 2 | 160425T015925Z | orlp |
| 011 | Fuzzy Octo Guacamole | 160410T142012Z | Riker |
| 005 | Alpax | 160326T202523Z | Adnan |
| 018 | Reng v.2.1 | 160325T011220Z | Conor O& |
| 106 | Scratch | 160318T145254Z | quat |
| 009 | PARI/GP | 160318T134046Z | Charles |
| 010 | Gogh | 160317T200418Z | Zach Gat |
| 018 | Julia | 160317T010500Z | Riker |
| 010 | DUP | 160307T035524Z | Mama Fun |
| 011 | CJam | 160302T153721Z | A Simmon |
| 033 | JavaScript | 110403T164658Z | aviraldg |
| 012 | beeswax | 151225T053345Z | M L |
| 051 | Lua | 160203T172140Z | TheCrimu |
| 045 | C | 160203T164313Z | Cole Cam |
| 080 | Oracle SQL 9.2 | 160203T154857Z | Jeto |
| 063 | CoffeeScript | 160203T130119Z | username |
| 135 | Oration | 160202T030629Z | Conor O& |
| 036 | 𝔼𝕊𝕄𝕚𝕟 | 160123T034332Z | Mama Fun |
| 466 | Brainf*ck | 160122T043247Z | takra |
| 039 | R | 160120T231251Z | lambrusc |
| 058 | C# 4 | 110818T104558Z | Jon Skee |
| 040 | R | 151215T101641Z | plannapu |
| 028 | Ruby | 151128T100046Z | Vasu Ada |
| 019 | GNU Octave | 151117T150056Z | user2958 |
| 389 | Turing machine code | 151103T170856Z | DLosc |
| 010 | Minkolang 0.10 | 151030T195844Z | El'e |
| 004 | TeaScript | 151028T173033Z | user4180 |
| 011 | Vitsy | 151029T091006Z | Addison |
| 041 | Java | 151021T153215Z | Geobits |
| 029 | dc | 151014T213644Z | user4620 |
| 451 | ArnoldC | 151014T034425Z | Mama Fun |
| 044 | Rust | 151014T133141Z | jus1in |
| 053 | Javascript | 151012T232738Z | Mama Fun |
| 038 | Python 3 | 151012T130144Z | m654 |
| 061 | Desmos | 151012T132841Z | Conor O& |
| 049 | Ruby | 151012T120705Z | dav_i |
| 011 | TIBASIC | 150708T234206Z | lirtosia |
| 020 | Julia 20 Characters | 150416T213600Z | Andrew |
| 026 | Octave | 150416T182235Z | pawel.bo |
| 012 | Prelude | 150125T142408Z | Martin E |
| 011 | JAGL V1.0 13 / | 141217T173858Z | globby |
| 027 | Ruby | 141124T143121Z | Kasran |
| nan | 141123T044643Z | averykho | |
| 010 | Perl 6 | 141121T184649Z | Marco Au |
| 010 | Befunge 98 | 140420T232914Z | Paul Tho |
| 027 | ~~! No Comment | 140407T171502Z | cjfaure |
| 033 | Forth 38 | 140331T173827Z | Michael |
| 063 | F# | 140331T213938Z | MarcinJu |
| 064 | C 64 Characters | 140331T151259Z | DollarAk |
| 108 | COW | 140112T173505Z | Timtech |
| 075 | PowerShell 42 or | 131128T201030Z | Iszi |
| 013 | Befunge | 131129T224343Z | FireFly |
| 004 | FAC Functional APL | 131130T103959Z | FireFly |
| 172 | BrainFuck | 120511T201138Z | Kevin Br |
| 4537 | C | 131128T204501Z | Stuntddu |
| 042 | F# | 131127T222405Z | goric |
| 108 | JAVA | 131127T215015Z | user1076 |
| 030 | Windows PowerShell – | 110129T222840Z | Joey |
| nan | 130417T175154Z | Troy Alf | |
| 026 | Mathematica | 130130T172608Z | chyanog |
| 026 | APL | 130408T042527Z | SL2 |
| 047 | C | 130404T040434Z | Fors |
| 021 | Haskell 27 | 130404T133643Z | Fors |
| 046 | Clojure | 130322T130442Z | Programm |
| 053 | Python 3 | 130321T191312Z | AMK |
| nan | 130319T185703Z | Christop | |
| 009 | Mathematica | 120201T200532Z | celtschk |
| 010 | J | 130307T164650Z | randomra |
| 039 | MATLAB/Octave | 130306T173418Z | nrz |
| 048 | Javascript | 130131T112855Z | Rastko |
| 039 | Perl | 120621T201627Z | Jay Chan |
| 049 | PHP | 110316T184111Z | detour |
| 038 | Clojure | 120307T112201Z | mnicky |
| 046 | PHP | 120207T175107Z | Cameron |
| 056 | Python | 120118T031938Z | elssar |
| 062 | C / Objectivec | 111227T175304Z | Rodrigo |
| 051 | Perl | 111004T011423Z | PhiNotPi |
| 091 | Python O1 Nth number | 110527T050957Z | Joel B F |
| 008 | CHIP | 110525T213435Z | Number23 |
| 052 | Scala | 110412T014141Z | user unk |
| nan | Python | 110406T050618Z | eordano |
| 048 | Common Lisp | 110405T001252Z | Dr. Pain |
| 036 | bc | 110404T145359Z | user unk |
| 012 | K | 110404T154529Z | isawdron |
| 025 | Ruby | 110404T114420Z | Matma Re |
| nan | 110228T172808Z | aaaaaaaa | |
| 020 | DC | 110201T130749Z | Hiato |
| 020 | J | 110130T093125Z | Eelvex |
| 100 | Bash | 110130T002354Z | Alexandr |
| 012 | GolfScript | 110129T215530Z | jtjacque |
| nan | 110128T015740Z | Alexandr | |
| 036 | Python | 110128T015318Z | Alexandr |
| 013 | GolfScript | 110128T015035Z | C. K. Yo |
Nekomata + -n, 4 bytes
ᴶ#3<
ᴶ#3<
ᴶ# Non-deterministically split the range [0,input) into parts,
and take the length of each part.
3< Check if all lengths are less than 3.
The flag -n set the interpreter to CountValues mode, which counts the number of possible results.
Nekomata + -n, 6 bytes
ʷ{←Pᶜ←
The flag -n set the interpreter to CountValues mode, which counts the number of possible results.
It takes an integer as input, and prints the Fibonacci number at that position.
ʷ{←Pᶜ←
ʷ Repeat the following function until it fails.
{ Start a block.
← Decrement the top of the stack.
P Check if the top of the stack is positive. If it is, keep the element unchanged. If it is not, fail.
ᶜ Optionally apply the following function.
← Decrement the top of the stack.
Nekomata, 7 bytes
1:ᶦ{$ᵉ+
This takes no input and prints all the Fibonacci numbers.
1:ᶦ{$ᵉ+
1 Push 1 onto the stack.
: Duplicate the top of the stack.
ᶦ Iterate the following function zero or more times non-deterministically.
{ Start a block.
$ Swap the top two elements of the stack.
ᵉ Apply the following function, and then push the original top of the stack onto the stack.
+ Add the top two elements of the stack.
Python 3.8, 33 chars
lambda n:pow(p:=2<<n,n,p*p+~p)//p
Explanation
p*p+~p is equivalent to p*p - p - 1, the characteristic polynomial of the fibonacci sequence. This means that if we had the polynomial x*x - x - 1, then the nth fibonacci number is just the coefficient of x in x^n modulo (x*x - x - 1). However we are using a concrete integer p instead of a transcendent x element. The trick here is that p = 2**(n + 1) is large enough that the result does not "overflow" into the coefficients of the other polynomial coefficients. The last //p then just extracts the coefficient of x, since the result polynomial is at most of degree 1 (since we are getting the result modulo a degree-2 polynomial) and the constant coefficient is ignored.
h6, 28 bytes
f:{.{;1}${1-.1-f!$f!+}$2>?!}
h6 is a new stack language by alex-s618, and it's pretty cool!
This fibonacci function is pretty simple: it makes a function {;1} which takes a number and returns 1, and {1-.1-f!$f!+} which does f(n-1)+f(n-2), and conditionally applies one to the input.
awk
—- a POSIX-compliant Fibonacci sequence generator for awk that generates at double speed while having zero amounts of external dependencies, hard-coded thresholds, function calls, or semi-colons, for that matter.
golfed
function ____(__,___,_){if((___=((__+=_++)-(__%=++_))/_)||
_<(_=__))for(__||__=--_;--___;)_+=__+=_;return _}
ungolfed
jot 76 | awk '$++NF = ____($!_)_
function ____(__,___,_) {
if ((__ += _++) <= ++_)
return !!__
else (___ = (__ - (__ %= _)) / _) < (__ ||
__ = --_)
while (--___)
_+=__+=_
return _
}'
1 1 20 6765 39 63245986 58 591286729879
2 1 21 10946 40 102334155 59 956722026041
3 2 22 17711 41 165580141 60 1548008755920
4 3 23 28657 42 267914296 61 2504730781961
5 5 24 46368 43 433494437 62 4052739537881
6 8 25 75025 44 701408733 63 6557470319842
7 13 26 121393 45 1134903170 64 10610209857723
8 21 27 196418 46 1836311903 65 17167680177565
9 34 28 317811 47 2971215073 66 27777890035288
10 55 29 514229 48 4807526976 67 44945570212853
11 89 30 832040 49 7778742049 68 72723460248141
12 144 31 1346269 50 12586269025 69 117669030460994
13 233 32 2178309 51 20365011074 70 190392490709135
14 377 33 3524578 52 32951280099 71 308061521170129
15 610 34 5702887 53 53316291173 72 498454011879264
16 987 35 9227465 54 86267571272 73 806515533049393
17 1597 36 14930352 55 139583862445 74 1304969544928657
18 2584 37 24157817 56 225851433717 75 2111485077978050
19 4181 38 39088169 57 365435296162 76 3416454622906707
Generating at 2x speed is simpler code than 1x speed, because a back-to-back variable swaps self cancels out, figuratively speaking.
SAKO, 60 bytes
1)CZYTAJ:N
B=.5
DRUKUJ(9,0):(B+B×5*B)*N/5*B
STOP1
KONIEC
Pretty basic solution printing N-th number using Binet's formula.
SAKO, 67 bytes
A=1
B=1
TEKST
1
1)DRUKUJ(9,0):B
B=B+A
A=B-A
SKOCZDO1
KONIEC
This one generates the Fibonacci sequence without end.
- Set
AandBto1, print it. - Set
AtoB, andBto next Fibonacci number. - Print
B. Go to point 2.
Both solutions start printing in E notation for numbers longer than 10 digits, although at that point floating point inaccuracies probably already accumulated.
APL(NARS), 16 chars
{⍵≤1:⍵⋄+/∇¨⍵-⍳2}
Just one recursive function from the definition of Fibonacci sequence.
{⍵≤1:⍵⋄+/∇¨⍵-⍳2}¨0,⍳10
┌11────────────────────────┐
│ 0 1 1 2 3 5 8 13 21 34 55│
└~─────────────────────────┘
This below is one other entry that can calculate even fibonacci(100000) (at last)
APL(NARS), 43 chars
r←q w;h;k
h←0x⋄k←1x
r←h⋄h←k⋄k+←r⋄→2×⍳0≤w-←1
// 9+9+23+2=43 test:
q ¨0,⍳10
0 1 1 2 3 5 8 13 21 34 55
q 300
222232244629420445529739893461909967206666939096499764990979600
APL(NARS), 42 chars
{⎕fpc←2e4⋄1⍕((⍵*⍨2÷⍨1+h)-⍵*⍨2÷⍨1-h)÷h←√5v}
This until input 10000 should be ok. It seems there is this formula for find fibonacci numbers:
f_n=( ((1+√5)/2)^n - ((1-√5)/2)^n) )/√5 for n in 0..+oo
but the function q find easy a fibonacci number with n = 100000 because use rationals not big float...
TinyAPL, 12 bytes
{>⦅+/,>⦆⍣⍵1}
Output the first of repeatedly making the list (sum, first) N times, starting with 1.
(Taking the sum or the first item of just 1 gives 1.)
And yes, it is shorter to just port the classic APL solution using Pascal's triangle - that comes out to 10: ⦅0+/·!⟜⊖⍳⦆
TinyAPL, 14 bytes
{⊇+/∙×⍣⍵⍨⊤3‿2}
Thanks @noodle person for -1
Explanation
The solution is based on the matrix definition of Fibonacci numbers: \$\displaystyle \left[\matrix{1 & 1 \\ 1 & 0}\right]^n = \left[\matrix{F_{n + 2} & F_{n + 1} \\ F_{n + 1} & F_n }\right] \$
{⊇+/∙×⍣⍵⍨⊤3‿2}
⊇ ⍝ The bottom-right entry of
+/∙×⍣⍵⍨ ⍝ the matrix power ⍵
⊤3‿2 ⍝ starting with [1‿1 ⋄ 1‿0]
💎
Created with the help of Luminespire.
Jalapeño, 11 bytes
1‽{₃⇥P1‥{₂⇥ₓ2Σ
Runs forever printing every fibbonacci number along the way. Very quickly succumbs to Double number precision error though.
Explained
1‽{₃⇥P1‥{₂⇥ₓ2Σ
1 # Constant value 1 as the initial state for the while loop
‽ # state -> While condition(state) {state = body(state)}...
{₄ # The condition consisting of the next 3 links
⇥P # Print the last element of the list
1 # Constant value 1, run forever
‥ # Concatenate to the end of the state...
{₂ # The result of the next 2 links...
⇥ₓ2 # Tail 2, the last 2 elements of the list
Σ # Sum of
Hex-Dump of Bytecode
0 1 2 3 4 5 6 7 8 9 A B C D E F
0000: 31 a2 c7 dc 10 31 2e c6 df 32 e9
Try it Online! WARNING Might crash your browser.
Periodically, 41 bytes
H4(BrI)2ITiCo[ClICaICIKOScI2FO2KCoI3BCo]3
explained: (not valid code)
H4 | initialize tape with 4 elements
(BrI)2 | set vars[0] to 1 and vars[1] to 2
ITi | get user input, set it to vars[3]
Co | reset argument tape
[ | do...
Cl | print vars[0] to console
ICa | add vars[0] to vars[1]
ICIK | copy vars[1] to vars[2]
OSc | subtract vars[2] by vars[0]
I2FO2K | copy vars[2] back to vars[0]
Co | reset argument list
I3B | subtract vars[3] by 1
Co | reset argument list again
]3 | ...while vars[3] > 0
TSQL, 110 bytes
-23 bytes
-21 bytes
Outputs the n-th number of the Fibonacci sequence.
The 110, 131 and 154 byte versions works up until n=46 (due to integer outflow starting with Fib(47)==2971215073 > 2**31 -1).
Although we can sacrifice 9 bytes to convert three variables to BIGINT to allow computation of the fibonacci sequence up until Fib(92)==7540113804746346429 < 2**63 - 1.
110 byte solution
DECLARE @ INT=0,@A INT=0,@B INT=1,@C INT=0
WHILE @<##I##
BEGIN
SET @=@+1
SET @A=@B
SET @B=@C
SET @C=@A+@B
END
PRINT @C
163 bytes, commented out
DECLARE @ INT
DECLARE @A BIGINT --Now we can have values up to 2**63 - 1, or
DECLARE @B BIGINT --9223372036854775807. Or just bigger than Fib(92) :D
DECLARE @C BIGINT --And Fib(92) still is returned in <1ms.
SET @A=0 -- _________________________________________
SET @B=1 --| Just setting up the Fibonacci stuff. :\ |
SET @C=0 --| Basically just initializing variables. |
SET @=0 --|_________________________________________|
-- _________________________________________________________
WHILE @<##I## --| |
BEGIN --| Recursion starts here. Note that ##I##==0 automatically |
--| exits this and returns 0 |
SET @=@+1 --|_________________________________________________________|
SET @A=@B
SET @B=@C
SET @C=@A+@B -- ________________________________________________________
--| If `@` reaches our input or crash due to int overflow. |
END --|________________________________________________________|
-- _________________________________________________________
PRINT @C -- | Final value (if we don't crash due to integer overflow. |
-- |_________________________________________________________|
Try it online!
110 bytes
131 bytes (old)
154 bytes (old)
163 bytes
Was learning recursion in T-SQL and decided to implement this :)
If anything the reason I'm posting this is because I'm just surprised nobody has posted an answer in any form of SQL despite it having recursion capabilities, although sorry for the late answer.
Hatchback, 57 45 32 30 bytes
0 0 1 2 1 0 17 0 1 1 0 0 65281
since Hatchback has an integer limit of 0xFFFF, it stops at 9227465 and errors out.
it doesnt need 65535 at the end because it loops until error lol
Javascript, 30 bytes
By the same criteria as lmcanavals's submission:
.5+(.5*5**.5+.5)**++n/5**.5>>0
or alternatively:
_=.5;_+(_*5**_+_)**++n/5**_>>0
If one is content with calculating the n-1-th Fibonacci number for a given n, both solutions reduce to 28 bytes:
.5+(.5*5**.5+.5)**n/5**.5>>0
and
_=.5;_+(_*5**_+_)**n/5**_>>0
Bespoke, 118 bytes
when I said n climbed quickly
it does,really
n got as big as needed
as much as if pairs together went in groups,said I
Outputs the Fibonacci sequence forever, separated by spaces.
Vyxal 3.5, 6 5 bytes
After nine two years in development, hopefully it will have been worth the wait.
11f⎄+
jbasher2, 155 bytes
create a with type number
set 1 to a
create b with type number
while 0 < 1
add b by a
set that to b
subtract b by a
set that to a
output a
endwhile
the worst code golfing language lol. no explanation because the code is already pretty verbose
punchcode, 25 bytes
[SOH][SOH][RS][SOH][BS][SOH][NUL][STX][SOH][EOT][NUL][STX][ETX][ETX][SOH][ENQ][NUL][STX][NUL][ETX][ETX][VT][STX][STX][CR]
hexdump:
00000000 01 01 1E 01 08 01 00 02 01 04 00 02 03 03 01 05 |................|
00000010 00 02 00 03 03 0B 02 02 0D |.........|
uncompiled:
-START |
-------O|
-------O|
---OOOO-|
-------O|
----O---|
-------O|
--------|
------O-|
-------O|
-----O--|
--------|
------O-|
------OO|
------OO|
-------O|
-----O-O|
--------|
------O-|
--------|
------OO|
------OO|
----O-OO|
------O-|
------O-|
----OO-O|
Python 3.8 (pre-release), 108 bytes
Neither short nor pretty, but possibly a new method!
def f(n):getcontext().prec=n*n-n+1;q=Decimal(100**n);return int(str(q/(q+~10**n))[-n:])
from decimal import*
Less golfed version:
Python 3.8 (pre-release), 126 bytes
from decimal import*
def f(n):l=n//4+1;p=10**l;getcontext().prec=n*l-l+1;return int(str(Decimal(p**2)/Decimal(p**2-p-1))[-l:])
Uses, for example:
1/(1000000-1000-1) = 0.000 001 001 002 003 005 008 013 021 034 055 089 ...
l can be any upper bound for the number of digits of the Fibonacci number after the one we want.
TypeScript’s type system, 97 bytes
//@ts-ignore
type F<N,L=[],A=[1],B=A>=L extends{length:N}?A["length"]:F<N,[...L,1],B,[...A,...B]>
This is a generic type F taking a number type N and outputting the Nth Fibonacci number, 0-indexed.
This solution won’t work past the first 20 Fibonacci numbers because of the max int (technically, max tuple size) limit.
Explanation: We start with the input number N, and L=[],A=[1],B=A. L keeps track of which Fibonacci number we’re on, and A and B are unary numbers (tuple-types of 1s) that track \$ f(n) \$ and \$ f(n + 1) \$ respectively.
First, check if L extends{length:N} (the length of L is N). If it is (?), return A["length"] (A as a decimal number).
Otherwise (:), recurse (F<…>), keeping N the same, increasing L’s length by 1 ([...L,1]), setting A to B, and setting B to A + B ([...A,...B]).
Alternatively, this can be done in 77 bytes with I/O in unary:
//@ts-ignore
type F<N,A=[1],B=A>=N extends[1,...infer N]?F<N,B,[...A,...B]>:A
Labyrinth, 13 bytes
1
:!\
{ :
=+}
Infinitely prints fibonacci numbers separated by newlines.
1 Set up the stack to [(implicit 0) 1]
Loop with stack content [x y]:
:!\ :!\ print y and a newline
{ : :} [x y | y]
=+} + [x+y | y]
= [y | x+y]
{ [y x+y]
Trilangle, 14 bytes
.'L1pj2'.S#1+|
Goes on forever in theory, but in practice it runs into the integer limit pretty quickly and spews garbage data.
You can try it on the online interpreter, but be ready to hit "stop program".
Unfolds to this:
.
' L
1 p j
2 ' . S
# 1 + | .
Basically does this:
var x = 1, y = 1
while true {
print(x)
(x, y) = (y, x + y)
}
Swift, 31 bytes
var f={$0<2 ?1:f($0-1)+f($0-2)}
Python 3.8, 36 bytes
I did not come up with this solution, so I'm making it Community wiki. However, it's beautiful, and you should read the blog post about it, from which I got the program.
lambda n:(b:=2<<n)**n*b//(b*b-b-1)%b
Uiua, 12 chars
|1 ⍥ (+,,) ↶ .1
Explanation:
.1 - repeat last item on stack: essentialy gives 1 1
↶ unroll - takes your user input (an natural number) and makes it the argument to the repeat
(+,,) - the function to repeat. it take the last two items from the stack, sum them and push to the top
⍥ - repeat modifier, takes the function and number of repeats as arguments
|1 - tells the compiler how many args to take as input
ELF executable (x64), 194 bytes
This is my first non-trivial assembly program, so there may be still room for improvement
hexdump:
457f 464c 0102 0301 0000 0000 0000 0000
0002 003e 0001 0000 0078 0040 0000 0000
0040 0000 0000 0000 0000 0000 0000 0000
0000 0000 0040 0038 0001 0040 0000 0000
0001 0000 0007 0000 0000 0000 0000 0000
0000 0040 0000 0000 0000 0040 0000 0000
00c2 0000 0000 0000 0142 0000 0000 0000
1000 0000 0000 0000 ff48 50c0 e853 0007
0000 5b58 0148 ebd8 48f2 c6c7 0141 0040
3148 b3db 880a b21e 4001 d788 3148 48d2
f3f7 8640 40d7 c780 4830 ceff 8840 fe3e
48c2 f883 7500 40e2 01b7 3148 b0c0 0f01
c305
prints decimal representation of Fibonacci-numbers (truncated to last 64 bits) indefinitely
assembly code (fasm):
format ELF64 executable 3
segment readable writable executable
_start:
inc rax
; rbx is initialized to zero
.loop:
push rax
push rbx
call print
pop rax ; old value for b
pop rbx ; old value for a
add rax,rbx ; (a,b) -> (b+a,a)
jmp .loop ; loop infinitely
print:
mov rsi,buffer_end ; point to end of buffer
xor rbx,rbx
mov bl,10 ; store 10 in rbx
mov [rsi],bl ; append new-line
mov dl,1 ; length
.loop:
mov dil,dl ; more counter to rdi
xor rdx,rdx ; clear rdx
div rbx ; divmod: quotient -> rax remainder -> rdx
xchg dl,dil ; move remainder to rdi (and length to rdx)
add dil,48
dec rsi
mov [rsi],dil ; *buffer=n%10
inc dl ; length++
cmp rax,0
jne .loop ; go back to loop if rax if not zero
mov dil,1 ; stdout
xor rax,rax
mov al,1 ; sys_write
syscall
ret
print_buffer rb 128
buffer_end = $-1
Headass, 26 bytes
UODONOE.U)UP:R-OU^[U]ODONE
Try It Online! - 1 indexed
Just realized I hadn't done this challenge after doing a fibonacci related code challenge. This code is just ripped from a section of my answer to that question.
Explanation:
UODONOE. code block 0
UO i = input
DO a = 0
NO b = 1
E go to code block b (1)
. end code block
U)UP:R-OU^[U]ODONE code block 1
U) : NE while(i){
R-O i--
U^ r1 = a
[ r2 = a
U]O a = b + r2
DO b = r1
NE } (go to code block 1)
UP print a
Dyalog APL, 17 characters (17 bytes SBCS)
{({⍵,+/¯2↑⍵}⍣⍵)⍺}
The arguments are the initial sequence on the left, and the number of additional terms to generate on the right. The call can be made shorter by replacing the ⍺ with 1, but then it can't generate an arbitrary sequence, only the one the question is actually about. Incidentally, replacing the + with a - will produce the other half of the sequence.
As a bonus, the Java answer mentions Binet's formula (with rounding), which I happened to have already written down (23 characters):
{⌊.5+(⍵*⍨+∘÷⍣=⍨1)÷5*.5}
Itr, 6 bytes
1#Måâ+
takes n as input, computes the n-th Fibonacci number (0-indexed)
Explanation
1 ; push 1
#M ; for every number in the 1-based range to the input
å ; ignore that number
â ; push the top value below the 2nd value
+ ; add the top two values
; implicit output
Itr , 10 bytes
Directly computes the n-th Fibonacci number using Matrix powers, sadly a bit longer than the other solution
1ä,1)#^M¡M
takes n as input, computes the n-th Fibonacci number (1-indexed)
Explanation
(1ä,1) ; the matrix [[1,1],[1,0]] (the opening bracket at the start can be left out)
^ ; to the power of
# ; the input
M¡M ; get the lower left element
M¡ ; push the rows of the matrix reversed
M ; push all elements of the reversed lower row
ForWhile, 11 bytes
{1'[';+:).}
takes number n on stack as input, returns nth Fibonacci number
Explanation
{ } \ anonymous procedure
1' \ push 1 below argument
[ :) \ repeat n times
' \ swap the top two values on the stack (A B -> B A)
; \ copy the lower value above the higher value (B A -> B A B)
+ \ add the op two stack elements (B A B-> B A+B)
. \ discard the top stack element (only return one Fibonacci number)
Thunno 2, 2 bytes
ÆF
Given n, outputs the nth Fibonacci number (1-indexed).
Built-in solution. In Thunno 2.1.5, a non-built-in alternative will be 4 bytes:
1µµ+
Starting from 1, generates an infinite sequence (µµ), where the next term is found by adding (+) the previous two terms together.
Screenshot
Thunno Y, \$7 \log_{256}(96) \approx\$ 6 bytes
(actually 5.76 bytes but that doesn't show up on the leaderboard)
{xyAx+Y
Returns the 0-indexed \$n\$th Fibonacci number.
Explanation:
{xyAx+Y # Implicit input
{ # Loop that many times:
xy + # Add x and y together
yAx # While storing y in x
Y # And storing the result in y
# After the loop, the Y flag pushes y
# Which is output implicitly afterwards
Note that x defaults to 0 and y defaults to 1.
Brachylog, 10 9 bytes
1⟦⟨t≡+⟩ⁱh
Generates an infinite list of Fibonacci numbers through the output variable.
1⟦ Starting with [0, 1],
ⁱ iterate some (possibly zero) number of times:
⟨ ≡ ⟩ pair
t the last element with
+ the sum of the two elements.
h Yield the first element of the result.
Brachylog, 14 12 bytes
0;1⟨{tẉ₂}↰+⟩
Prints terms infinitely, separated by newlines.
0;1 Starting with [0,1],
{tẉ₂} get and print the second element,
+ sum the two elements,
⟨ ↰ ⟩ and recur on the pair of those two values.
A variant to find the nth term of the sequence, 0-indexed:
Brachylog, 13 bytes
∧0;1⟨t≡+⟩ⁱ↖?t
Rattle, 9 bytes
+s[p+~$]0
Note: the link only runs this loop 100 times instead of infinitely because the online interpreter behaves strangely with an infinite loop for this code (which is a problem with the website, not the interpreter).
Explanation
+s increment the top of the stack (to 1) and save to memory
[ ]0 infinite loop
p print top of stack
+~ increment top of stack by the value in storage
$ swap the value on top of the stack with the value in storage
Haskell + hgl, 11 bytes
yy$K1<.<scp
Uses a new version that doesn't work on ATO yet :(
Explanation
The basic idea is to use the fact that each element of the sequence is one more than the sum of all elements 2 or more steps before it.
For example, by the time we have
1,1,2,3,5,8
To get the next element we sum everything but the last element (8)
1+1+2+3+5 = 12
and add 1
1,1,2,3,5,8,13
If we set up the first two elements we can use this property to generate the entire sequence.
yy is the fixed point combinator, it can be very hard to understand if you aren't used to wacky recursive schemes, so we will just rewrite things without it:
f=K1<.<scp$f
<.< is a fancy compose which composes its first argument on both sides of the second, so once again we can rewrite this longer as:
f=K1<scp<K1$f
K1 is a shortcut for (1:) which adds 1 to the front of a list.
f=1:(scp$1:f)
scp gives the cumulative sums of a list. This is the part that establishes the property which builds the next element.
11 bytes
f=1:lS(+)1f
Explanation
This pretty straight-fowardly ports the Haskell answer. Same score as the other one but less interesting.
Reflections
There are some nice things here, I feel the first answer works well and I'm happy with the functions it is using. But I can still see somethings that could probably be improved.
- There should be builtins for dealing with Fibonacci numbers eventually. They are a common subject of code-golf challenges
lS mpis probably useful.scpandscsare very similar, however they are required to not alter the length of the structure involved, whilelS mpalways makes the structure one longer. This is essential for the second answer to work, so we can't usescsas a replacement.
Seed, 4694 4502 bytes
39 23345386873944734309285705649562214322923535338513787840726059344836991733232701124858784406171983413525769035739193091317312821286862091673034093258254737808529480740867073160694207283540732802589654087348246306424108351751311067631335648365532710947883728455312678903999543414986443810435493370315134647072481870757046559560767136040676281671376819795324434856453735428264762843673716931661746853554648863000837820618766325590788356124601042099541341483064315601051750207795784533758073620813013115058115202328602261019521188162907432705317709462265407997435677959431637608739188384820535674569023665708824769117130584628086812767619300150936306513016713438624735631896208226558553705578499273228365561706607508974248633654644472401969256417949202545503229189330457914013293106347633234904257897628188377211123547522316430704423351649833550317940803484242023657434716958957587230473447472170005697587796499855927956924703860969370032077181183813997697920001129271041258462117064842855557817828287309864524148521039064850419014169734078927801370682493891194692916817142423371375512874755307643229558474820620773013367601053438535142499961672800471263088573030714197841432529737819978024272023115971994335629080760807110601625840500005576870897474597727212673444634680054468191797452281171657965522840129388173724585980135600170025063620602628298627811946062091546889131371926823568681212834659514998682306098670560578318063077703702015608052686405555782215469820110984687203004291914156230320625462064509758167591458209331235212640744714944466265540624319127738893716421169144022527159634296736260757337640921918849758954315864968212488657203226533587353649351778992581839569265033006103790337825946891770665589403131544197363786202809251067880755092540881383788858825619755294045426872602952477879200662412263820311579658891410984567942455376104064634087560919309116469779337448222971714205506106434861563361065264676346668562754032388044586603191705003186050941101737238753507972188516844227916598403811945061789829209022797794856907795280845148337927336190754837895578035971541077446106601429711198909985434167448288125565008326994953358507196336677928811063398215196756813330927829954298340363790942335608247284708980931664255175263323494474655761771711383684020341286483311232450751637188832338282365001980619004736926421020545780168645284628043949398052855672494054844858796879547004560821501647027627620931639915989753539985160519138882067784198444595441811191399424880792691274895217945599103951284792036009843684640644727200173221626567038906492094115422297154223582626065131092394499833564570471955561529154762920901660552470118203300492660926353444889031479441391716424199093929419050805652092712224713014163928963683320445942834620765638299957157761471954992453965174566767052457734421384797861892548612233678879032571407415763995799697084460449481011980933595196444998930307697403672188673825999360332797937744985054511100836407779016165673872373310879592118399300133957780585475517066306666920397584925551254210311998315301028471463539416320653567122160674748915331494295984381121190145666938252633808615711556028673805375510446823318750130981978154654997326727239404525161535622829359058005003740269566983082692378752252198224696254750416200980706704359975518565261545420238758226454680563033057001226125143840414367435620075434502664984902148647078854467653648067041037379150849558209574954581189083630370505506375071080959718696461782683034278484505125465265492405192125616634322283908654348532913099106491870966062276727286614470801650571178850146397543614007581120988735292604484768834605242986004904531743614154630006898576385883749714930636531225280325429278056803694383205579251797535306160456389603169599349989707250713018909969811190663566801819447003975601708056252841800628364818930316430260043879135073603348919031644234002981192629576497660461677947610006543231706577837438811265977164354969644885825582261812180155492583995120383156018469389467006878690072374841382066122175919585112489442594496493463386891710103741087324632245353507660394419350165419526162955982962335197477336304033108148298040661871462588450794544521467248068540365914505422139306015926783904272029251862004795498004645359369772500371366215160030879374914060894959826814924777847813129579229461420328680050563398486579073401384070598971755243256100966805691895631455236232588087146040702221938793149485419052426135144305222421870942178316091451568136489010664122415628294236744095902991276097097917
Befunge-98 (PyFunge), 39 bytes
31p132p>31g32g:.+ v
^,p23p13g23<
I'll throw this into my Seed generator and see if it gives me anything good.
Excel, 52 50 bytes
=INDEX(ROUND((.5+SQRT(5)/2)^ROW(A:A)/SQRT(5),),A1)
Note: Excel will automatically add a leading zero to .5 after you input the formula.
If you put a value in A1, you get that term (1-indexed) from the sequence. If you leave it blank, you get the first 1,474 terms which is when it gets too large for Excel to handle. As you can see below, it also loses accuracy at some point because Excel only keeps the first 15 digits of a number.
J-uby, 8 bytes
This is straight from the J-uby README.
:++[0,1]
Explanation
From the README:
(F+init).(n)starts an array with init, then appliesFto the lastinit.lengthentriesntimes
In this case, init is [0,1] and F is :+, i.e. add.
Nibbles, 4.5 bytes (9 nibbles)
.~~1+<2
.~~ # append until null (here this means forever)
1 # starting with 1
+ # sum of
<2 # take 2 elements (or 1 if there's only 1)
Nibbles also supports a recursive approach to calculate the n-th element:
``; $ -$2 1 + @-$2 @-$~ (10 bytes = 20 nibbles)
``; # define a recursive function:
$ # initial input is arg1;
-$2 # when input minus 2 is zero or negative:
1 # return 1;
# otherwise:
+ # add together
@-$2 # recursive call with input minus 2
@-$~ # and recursive call with input minus 1
...although simply indexing into the infinite sequence is shorter: =$.~~1+<2 (5 bytes = 10 nibbles).
Python 33 bytes
x,y=0,1
while 1:print x;x,y=y,x+y
This will be an infinite loop!
Python 31 bytes
def f(a=[1,0]):a[:]=a[1],sum(a)
demonstration
for _ in range(10):
f(); print f.func_defaults[0][0]
0
1
1
2
3
5
8
13
21
34
Ruby, 29 27 25 24 bytes
p a=b=1;loop{b=a+a=p(b)}
Edit: made it an infinite loop. ;)
K - 8 bytes
+/[;1;0]
Explanation
It makes use of ngn/k's recurrence builtin.
How to use
Calculates the nth fibonacci number.
To calculate the nth put the number at the end of the program:
+/[;1;0]40
HOPS, 10 bytes
seq(x+x^2)
HOPS, 11 bytes
1/(1-x-x^2)
The generating function of the Fibonacci sequence is \$1/(1-x-x^2)\$. In HOPS, seq(f) means 1/(1-f).
Fig, \$4\log_{256}(96)\approx\$ 4.125 3.292 bytes
G:1'+
New language! Yay! This is a fractional byte language I've been advertising on TNB for a while now. It's pure printable ASCII, and has a 97 96 char codepage. Although the spec is mostly written by now, this commit only has the bare minimum implemented for this challenge. To run this, check the README.
It will print Fibonacci numbers until your computer runs out of RAM. Explanation:
G1'+ - Takes no input
G - Generate an infinite list using initial terms...
1 - 1...
' - And the generating function...
+ - Addition (the initial terms are repeated to fit the arity)
APL(Dyalog Unicode), 16 bytes SBCS
{⊃⊃(+/,⊃)⍤⊢/⍵/1}
Straightforward "repeatedly add previous two elements" style approach. Not as short as using pascal's triangle, but I'm still pretty proud of this :-)
-1 thanks to Adám for reminding me of the atop operator, also known as the "atoperator". Also from Adám, an optional "full program" version of this for -2:
⊃⊃(+/,⊃)⍤⊢/⎕/1
Code breakdown:
{⊃⊃(+/,⊃)⍤⊢/⍵/1} full dfn
⍵/1 make a list of n 1s
/ reduce over them with the following tacit function
⍤⊢ apply the following tacit function(?) to only the
previous element (in js, think (a,b)=>f(a))
( , ) return a list of
+/ sum of elements ([5,3]=>8)
⊃ first element ([5,3]=>5)
⍝([5,3]=>[8,5])
after the reduce, you're left with
a scalar of the value [fib(n),fib(n-1)]
⊃ take the first element of this scalar (the array)
⊃ take the first element of the array (this is the end result)
As you can see, I'm still learning how APL works :P
If there are any terminology fixes you want to make in my explanation, go ahead; You have my blessing.
ShapeScript, 16 14 bytes
_1@0@'@1?+'*!#
This reads an integer n (in unary) from STDIN and prints the nth Fibonacci number.
How it works
Input: a string of n 1's
_ Get the length of the input to push n.
1@ Swap it with 1 (F[-1]).
0@ Swap it with 0 (F[0]).
STACK: F[-1] F[0] n
' Push a string that, when evaluated for the i-th time,
does the following:
@ Swap F[i-2] on top of F[i-1].
1? Push a copy of F[i-1].
+ Add the copy of F[i+1] to F[i].
' STACK: F[i-1] F[i]
*! Repeat the string n times and evaluate it.
# Discard F[n] from the stack.
Hexagony, 6 bytes
1.}=+!
Ungolfed:
1 .
} = +
! .
It prints the Fibonacci sequence without any separator.
Stackish, 12 bytes
01d\+.qzcl2'
How it works:
0 Load 0 into stack (stack now 0).
1 Load 1 into stack (stack now 0,1).
d Duplicate last number of stack (stack now 0,1,1).
\ Swap bottom with top (stack now 1,0,1).
+ Add last two numbers (stack now 1,1).
. Pop to output (stack now 1).
q Undo pop (stack now 1,1).
z Pause.
c Clear screen.
l2' Jump to 2nd character (d).
d Duplicate last number of stack (stack now 1,1,1).
\ Swap bottom with top (stack now 1,1,1).
+ Add last two numbers (stack now 1,2).
. Pop to output (stack now 1).
q Undo pop (stack now 1,2).
z Pause.
c Clear screen.
l2' Jump to 2nd character (d)
...
JavaScript (ES6) - 24 Characters
f=x=>x<3?1:f(x-1)+f(x-2)
JavaScript - 24 Characters (snippet)
for(a=b=1;--n;a=b-a)b+=a
Set a value for n and it will calculate the nth Fibonacci value.
SunSip -w -n, 298 bytes
(just means disable warnings and newlines)
set a to
defined
set 5 to 5
calc multiplication 5 last
skip
set to "
in
calc int last
recurse
out
set to 1
calc greater a last
calc multiplication 5 last
skip
set to 1
exit
set 1 to 1
calc subtraction a 1
recurse
set b to
calc subtraction a 1
calc subtraction last 1
recurse
calc addition last b
A big fat 298 bytes but I'm still proud.
Syntax Highlighted:

Perl 5, 36 35 33 32 bytes
-2 bytes thanks to dingledooper
1x<>~~/^(..?)*$(??{++$i})/;say$i
This works by using the regex ^(..?)*$ to count how many distinct partitions \$n\$ has as a sum of the numbers \$1\$ and \$2\$.
For example, \$5\$ can be represented in the following \$8\$ ways:
1+1+1+1+1
1+1+1+2
1+1+2+1
1+2+1+1
1+2+2
2+1+1+1
2+1+2
2+2+1
This tells us that the \$F_5=8\$.
I had this basic idea on 2014-03-05 but it didn't occur to me until today to try coding it into a program.
The following two paragraphs explain the 33 byte version:
To count the number of distinct matches ^(..?)*$ can make in a string \$n\$ characters long, we must force Perl's regex engine to backtrack after every time the regex completes a successful match. Expressions like ^(..?)*$. fail to do what we want, because Perl optimizes away the non-match, not attempting to evaluate the regex even once. But it so happens that it does not optimize away an attempt to match a backreference. So we make it try to match \1. This will always fail, but the regex engine isn't "smart" enough to know this, so it tries each time. (It's actually possible for a backreference to match after $ with the multiline flag disabled, if it captured a zero-length substring. But in this particular regex, that can never happen.)
Embedded code is used to count the number of times the regex engine completes a match. This is the (?{++$i}), which increments the variable $i. We then turn it into a non-match after the code block executes.
To get this down to 32 bytes, a "postponed" regular subexpression embedded code block is used, $(??{...}) instead of $(?{...}). This not only executes the code, but then compiles that code's return value as a regex subexpression to be matched. Since the return value of ++$i is the new value of $i, this will cause the match to fail and backtrack, since a decimal number (or any non-empty string) will never match at the end of a string.
This does make the 32 byte version about 7 times slower than the 33 byte version, because it has to recompile a different decimal number as a regex after each failed match (i.e. the same number of times as the Fibonacci number that the program will output). Using (??{++$i,0}) is almost as fast as (?{++$i})\1, as Perl optimizes the case in which the return value has not changed last time. But that would defeat the purpose of using $(??{...}) in the first place, because it would be 1 byte longer instead of 1 byte shorter.
As to the sequence itself – for golf reasons, the program presented above defines \$F_0=1,\ F_1=1\$. To define \$F_0=0,\ F_1=1\$ we would need an extra byte:
1x<>~~/^.(..?)*$(??{++$i})/;say$i
In the versions below, (?{++$i})\1 is used for speed (at the golf cost of 1 extra byte), to make running the test suite more convenient.
Here it is as a (reasonably) well-behaved anonymous function (47 46 44 bytes):
sub{my$i;1x pop~~/^.(..?)*$(?{--$i})\1/;-$i}
Try it online! - Displays \$F_0\$ through \$F_{31}\$
The above actually runs faster than the standard recursive approach (39 bytes):
sub f{my$n=pop;$n<2?$n:f($n-2)+f($n-1)}
Try it online! - Displays \$F_0\$ through \$F_{31}\$
If that is golfed down using Xcali's technique it becomes even slower, at 38 bytes:
sub f{"@_"<2?"@_":f("@_"-2)+f("@_"-1)}
Try it online! - Displays \$F_0\$ through \$F_{31}\$
or with the same indexing as my main answer here, 34 bytes:
sub f{"@_"<2||f("@_"-2)+f("@_"-1)}
Try it online! - Displays terms \$0\$ through \$30\$
See Patience, young "Padovan" for more variations and comparisons.
Perl 5 -p, 28 bytes
1x$_~~/^(..?)*$(??{++$\})/}{
I've just learned now, 16 months after posting the main answer above, that Ton Hospel's Sum of combinations with repetition answer used this same basic technique, predating my post by 3 years.
By combining the tricks used in that answer with those already used here, the program length can be reduced even further.
Perl actually literally wraps the program in a loop using string concatenation when called with -p, which I was surprised to learn (I would have implemented it in Perl as an emulated loop). So when this program is wrapped in while (<>) { ... ; print $_} by the -p flag, it becomes:
while (<>) {1x$_~~/^(..?)*$(??{++$\})/}{; print $_}
while (<>) implicitly assigns the input from stdin, <>, to $_ (which isn't done when using <> normally) at the beginning of each iteration of its loop.
$\ is the print output terminator. By default it is empty, but the above program turns it into an integer by incrementing it on every possible match found by the regex. If only one number \$n\$ is sent to the program via stdin, followed by EOF, then upon exiting the loop $\ will actually represent the \$n\$th Fibonacci number.
The while (<>) exits when it encounters EOF, giving $_ an empty value. So then print $_ will print that empty value, followed by the value of $\.
As such, it defeats the intended purpose of the -p flag, as this program works properly when given a single value followed by EOF; if given multiple newline delimited values, it will output the sum of those Fibonacci numbers after finally being sent EOF (if running the program interactively, this would be done by pressing Ctrl+D at the beginning of a line).
Contrast this with an actually loopable Perl -p program at 37 bytes:
1x$_~~/^(..?)*$(?{++$i})\1/;$i%=$_=$i
If the same multiline input is given to the 28 byte program, this happens: Try it online!
Sadly, the $\ trick can't be used with say; it only applies to print. The $, variable applies to both print and say, but only comes into play if at least two items are printed, e.g. say"","".
Regex 🐇 (ECMAScriptRME / Perl / PCRE / Raku), 8 bytes
^(xx?)*$
Takes its input in unary, as a string of x characters whose length represents the number. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.)
Try it on replit.com (RegexMathEngine)
Try it online! - Perl v5.28.2
Attempt This Online! - Perl v5.36+
Try it online! - PCRE1
Try it online! - PCRE2 v10.33
Attempt This Online! - PCRE2 v10.40+
Try it online! - Raku
This uses the same technique as my Perl answer – it counts how many distinct partitions \$n\$ has as a sum of the numbers \$1\$ and \$2\$. But the focus here is on variations possible in the regex, treating the logic behind invoking it as a black box – as the language this answer is written in.
That block box doesn't just count the number of overlapping substrings that match (which would just be 1 with this regex, since it's anchored on both sides) but the number of ways in which different choices can lead to a full match (where choices are available, that is – in atomic constructs, the element of choice is eliminated). The counting of this is implemented by forcing the regex engine to backtrack at the end of any complete successful match (by turning it into a failed match), incrementing a counter every time that is done.
One interesting way to modify the Fibonacci sequence regex is to change its indexing. Getting the sequence to start one earlier, yielding \$0, 1, 1, 2, 3, 5, 8...\$, is trivial, but the others are interesting, and starting 4 later is where it begins to get difficult (and I'm sure it can be golfed better than I have so far). At certain point, it should become optimal to emulate (xx?)* in the extra space that is missing, but I haven't worked out how to do that yet.
2 earlier - 13 bytes - Try it online!: ^xx(xx?)*$|^$
1 earlier - 9 bytes - Try it online!: ^x(xx?)*$
original - 8 bytes - Try it online!: ^(xx?)*$
1 later - 10 bytes - Try it online!: ^x?(xx?)*$
2 later - 16 bytes - Try it online!: ^x?x?(xx?)*(^|)$
3 later - 22 bytes - Try it online!: ^x?x?x?(xx?)*(^|^x?|)$
4 later - 55 bytes - Try it online!: ^(?(?=xxx)(x?){4}(xx?)*|(|(x()?)?x$|(x\B)?x?(|$)?)?x*)$
To go 3 earlier or beyond, the rules would need to be extended to allow returning a negative sign via a capture group being set or unset (because there can't be a negative number of choices).
Trianguish, 152 135 bytes
00000000: 0c05 10d8 0201 40d7 0401 4110 4102 a060
00000010: 2c02 b080 2c02 8050 20e4 0211 0710 e209
00000020: 1110 4028 0d00 6020 2902 10c3 0802 a107
00000030: 02a1 0502 8027 0910 290b 1110 403b 0890
00000040: 204d 03d0 503c 0790 602a 1071 02a0 9027
00000050: 0280 b110 8111 0402 70e2 0501 402a 0202
00000060: 9106 1107 0291 0b11 0902 702b 1040 2a10
00000070: 6110 2102 9050 2802 70b1 1071 1104 1102
00000080: 02a1 0502 802c 05
Trianguish is my newest language, a cellular automaton sort of thing which uses a triangular grid of "ops" (short for "operators"). It features self-modification, a default max int size of 216, and an interpreter which, in my opinion, is the coolest thing I've ever created (taking over forty hours and 2k SLOC so far).
This program consists of two precisely timed loops, each taking exactly 17 11 ticks. The first, in the top right is what actually does the fibonacci part; two S-builders are placed in exactly the right position such that two things occur in exactly the same number of ticks:
- The left S-builder,
x, copies its contents toy - The sum of
xandyis copied tox
Precise timing is required, as if either of these occurred with an offset from the other, non-fibonacci numbers would appear in brief pulses, just long enough to desync everything. Another way this could have been done is with T-switches allowing only a single tick pulse from one of the S-builders, which would make precise timing unneeded, but this is more elegant and likely smaller.
The second loop, which is also 11 ticks, is pretty simple. It starts off with a 1-tick pulse of 1n, and otherwise is 0n, allowing an n-switch and t-switch to allow the contents of x to be outputted once per cycle. Two S-switches are required to make the clock use an odd number of ticks, but otherwise it's just a loop of the correct number of wires.
This program prints infinitely many fibonacci numbers, though if run with Mod 216 on, it will print them, as you might guess, modulo'd by 216 (so don't do that :p).
RASEL, 12 bytes.
1:.:3\01\--#
Chocolate, 4 bytes
G+c1
Explanation
G+c1
G ## Generate an infinite list...
+ ## With the addition function
c1 ## Starting from [1, 1]
Regenerate, 19 bytes
(($3!x)($1)!){$~1}x
The input \$n\$ is zero-indexed, taken as a command-line argument in decimal. The output is in unary, as a string of x characters whose length is the \$n\$th Fibonacci number.
( # Capture group $1 - unset on the first iteration, and on each
# subsequent, contains the previous iteration's match.
($3!x) # On the second iteration, match a single "x", seeding the Fibonacci
# sequence. On subsequent iterations, match $3.
($1) # Copy $1 into capture group $3, and also match it.
! # Try the below only when the above cannot match.
# Zero-width match - executed only on the first iteration, seeding
# the Fibonacci sequence.
){$~1} # Iterate the number of times passed as command-line argument #1.
x # Match a single "x", representing the 0th Fibonacci number.
This works similarly to Martin Ender's Fibonacci-matching regex, but it is freed from one of its limitations. To illustrate, a straight port of that regex would have been the following 23 byte Regenerate program (shown alongside this 19 byte one):
(($3!)($1)!x){$~1-1}x!x
(($3!x)($1)!){$~1}x
Martin Ender's regex has to work around the fact that any loop with an indefinite maximum iteration count will exit after making a zero-width match. But unlike a regex that must match any arbitrary Fibonacci number, for this problem we generate one from a known index, giving us a definite iteration count. Thus our first iteration can make a zero-width match.
A straight port of Martin Ender's regex to Regenerate is 4 bytes longer, because it's naturally "-1 indexed" rather than 0 or 1 indexed. So it needs {$~1-1} to fix the indexing; that in turn forces the need for a !x alternative at the end, because a negative number of loop iterations causes a non-match. If keeping it "-1 indexed", the two would be identical in length:
(($3!)($1)!x){$~1}x # -1 indexed: 1, 2, 3, 5, 8, 13, ...
(($3!x)($1)!){$~1}x # 0 indexed: 1, 1, 2, 3, 5, 8, ...
Regenerate, 30 bytes (26 characters)
((($4!)($2)!){$~1})${#1}
The output is in decimal. This is achieved by outputting the Fibonacci number in unary invisibly, using a string of Zero-Width Joiner (U+200D) characters instead of x, before outputting the length of that string in decimal using ${#1} (measured using by wrapping the entire unary regex in capture group $1, thus incrementing the previous capture group numbers).
Cubestack, 22 bytes
M R' M' z u2 b u2 R z'
Outputs forever in the offline version and in the online version it outputs as many as it can in 5 seconds.
Explanation:
M R' M' # Push 1 to the stack
z # Open an (infinite) while loop
u2 b # Without popping, print
u2 R # Without popping, add
z' # Close while loop
R, 23 bytes
repeat show(F<-T+(T=F))
Similar to, but shorter than, this answer, prints the sequence indefinitely. Based on this answer to a related challenge. Thanks to Dominic van Essen for some golfs.
GeoGebra, 38 bytes
n
InputBox(n
Iteration(p+q,p,q,{0,1},n
Input in Input Box. Outputs the nth term of the 0-indexed Fibonacci sequence starting at \$F_0=0\$, \$F_1=1\$.
Factor + benchmark.fib3, 3 bytes
fib
And a non- built-in version:
Factor, 32 bytes
[ 0 1 rot [ tuck + ] times nip ]
BitCycle -u, 67 45 bytes
v1< <
BvC1Av
v~~v <
> Cv>^
v~~
\>101!
It's beautiful... I have some idea of how this works.
The A, B and C are collectors. when the field is empty, the first non-empty collector (sorting in alphabetical order) has all collectors opened.
The basic idea is that the two numbers are stored in the B and A collectors. On each iteration:
- The bits stored in A are emitted into the main C collector
- The bits stored in B are duplicated and sent to the main C collector, and the C collector next to the A collector. This is necessary because otherwise the
Acollector would open before theCcollector. - Both
Ccollectors open. One emits its bits into A (previously stored in B). - The other duplicates its bits, and sends one stream to the B collector and the other stream to an output device
- Duplicating bits also emits negated bits. one of these (a 0) from the B collector is sent to the output device via the
\
This is because integer outputt in BitCycle is done in unary, with a sequence of n 1s and then a 0. a 0 must be sent before the next iteration begins.
The 101 is initially emitted to the output device to print 1, 1 (the 0 to print the next 1 is supplied before the 2 is emitted).
Nim, 38 bytes
var a,b=1
while 1>0:a=b-a;echo a;b+=a
Nim, 64 bytes, with arbitrary precision
import bigints
var a,b=initBigInt(1)
while 1>0:a=b-a;echo a;b+=a
Thanks to @JoKing and @cairdcoinheringaahing
Nim, 48 bytes
proc f(n:int):int=(if n<=2:1 else:f(n-1)+f(n-2))
Bytes counted using wc -c. This is the standard recursive function approach, as opposed to the iterative full program of my other answer.
flax, 3 bytes
1+ⁿ
Port of the Jelly answer. Takes input from stdin. Works similarly to the Jelly answer.
LOLCODE, 262 bytes
HAI 1
I HAS A x
GIMMEH x
x IS NOW A NUMBR
BOTH SAEM x 0
O RLY?
YA RLY
VISIBLE "0"
NO WAI
I HAS A a ITZ 0
I HAS A b ITZ 1
I HAS A c ITZ 0
IM IN YR l UPPIN YR i WILE BOTH SAEM i SMALLR OF i DIFF OF x 2
c R SUM OF a b
a R b
b R c
IM OUTTA YR l
VISIBLE b
OIC
KTHXBYE
Reads n from STDIN and returrns the nth Fibonacci number.
Quipu, 33 bytes
1&0&\n
[][]/\
^^/\0&
--++??
1&
++
Saved 4 bytes thanks to Jo King.
It prints the Fibonacci sequence separated by newlines.
Equivalent pseudocode:
a = [0, 0, 0] // implicitly
0:
a[0] = a[1] - a[0] + 1
1:
print a[0]
a[1] = a[0] + a[1]
2:
print "\n"
goto 0
PHP 4 (58 chars)
The function f will print $n Fibonacci numbers.
If $n = 0 f will take it for Infinity, then reach the PHP floating point limit and print NAN forever.
function f($n){for($i=!$j=0;$n-=print' '.$j=-$j+$i+=$j;);}
PHP with GMP (70 chars)
If GMP is available, it allow for arbitrary-length integers to be worked with.
So we can compute f(1e5), output will be 1,045,063,704 chars long with no precision loss.
function f($n){for($i=!$j=0;$n-=print' '.$i=gmp_add($k=$i,$j);$j=$k);}
Info: f(1e5) = 25974...46875 has 20,899 digits.
Mascarpone, 45 bytes
v['1.]v*'b<^[v{^vv'b>'a<[ab]v*'b<^a'
.:!]v*:!
Outputs the numbers in unary, separated by newlines.
High-level explanation (go read the language specification first):
I redefine the interpreter to have two symbols, a and b, which kind of act as variables. Each symbol's operation prints a certain amount of 1s, so they kind of act as numbers in unary, and the operation corresponding to the string ab prints out the sum of a and b. At the start, a corresponds to 0 and b is 1. Each step, I simultaneously redefine (a, b) = (b, a+b) and then I output the new value of a.
Slightly less high-level explanation:
I will replace the newline with N because its only function is to help push a newline character — it doesn’t actually do anything special in terms of the logic of the program.
Due to the longness of the program, I’ll divide this explanation up into parts.
The beginning:
v['1.]v*'b<^
This changes the current interpreter so that the symbol b corresponds to the operation of outputting a single 1. (a corresponds to a no-op by default, so it doesn’t have to be mentioned here).
The rest of the program:
I will use the notation [x] (where x can be any character) to mean “the operation the current interpreter associates with the symbol x’, since that’s a lot to type and I don’t have much margin space to write the explanation in.
[v{^vv'b>'a<[ab]v*'b<^a'N.:!]v*:!
[ :!]v*:! Loop forever:
v{^ Hard to explain
v Create a new interp,
'a< where a is assoc with
v'b> [b]
'b< and b is assoc with
[ab]v* [ab] (i.e. [a], then [b])
^ Set current interp := that interp
a Now run the op corresponding to a
'N. and print a trailing newline.
Lua, 40 36 bytes
Prints the infinite Fibonacci sequence. Saved 4 bytes by using a goto operator instead of a while loop.
i,j=0,1::a::j,i=i,i+j print(i)goto a
Halfwit, 5.5 bytes
n><?(:}+
Halfwit's an experimental golfing language where most commands fit within half a byte. It's stack-based.
n Push the context variable n, 1 in global scope
>< Push an empty compressed integer = 0
?( Input times, do the following...
Example with stack = [2, 3]
: Duplicate [2, 3, 3]
} Rotate stack right [3, 2, 3]
+ Add [3, 5]
And the next pair is now on the stack
The last one is implicitly output
Here, n(} take up one byte each, and ><?:+ take up half a byte each.
TypeScript's type system, 193 188 186 bytes
type L='length'
type T<N,U extends 0[]=[]>=U[L]extends N?U:T<N,[...U,0]>
type S<A,B>=T<A>extends[...infer U,...T<B>]?U[L]:0
type F<N>=N extends 0|1?N:[...T<F<S<N,1>>>,...T<F<S<N,2>>>][L]
There's no way to do I/O here, but we can use hovering to view the value (also note that the generated JS is empty):
Unfortunately, TypeScript has strict recursion limits and on F18 we get a Type instantiation is excessively deep and possibly infinite. error:
Ungolfed version:
type NTuple<N extends number, Tup extends unknown[] = []> =
Tup['length'] extends N ? Tup : NTuple<N, [...Tup, unknown]>;
type Add<A extends number, B extends number> =
[...NTuple<A>, ...NTuple<B>]['length'];
type Sub<A extends number, B extends number> =
NTuple<A> extends [...(infer Tup), ...NTuple<B>] ? Tup['length'] : never;
type Fibonacci<N extends number> =
N extends 0 | 1 ? N : Add<Fibonacci<Sub<N, 1>>, Fibonacci<Sub<N, 2>>>;
Hexagony - 61 bytes, return seperator
))')).............../{\/{\)))/=.(\=.+\\*{/..==..\>{;"!<.({("/
BQN, 17 13 bytes
(non-recursive version)
Edit: -4 bytes thanks to hints from ovs
{⊑+´⊸∾⟜⊏⍟𝕩↕2}
BQN, 17 bytes
(recursive version)
{𝕩>1?+´𝕊¨𝕩-1‿2;𝕩}
Python 3, 46 44 bytes
lambda n,a=5**.5:((.5+a/2)**n-(.5-a/2)**n)/a
Uses Binet's formula to derive the nth Fibonacci number.
Very wrong answer from me misreading the question:
g=lambda n:n+g(n-1)if n else n
jq -n, 30 28 bytes
-2 bytes thanks to Michael Chatiskatzi!
Prints the infinite sequence.
[0,1]|while(1;[last,add])[1]
Start with [0,1].
while(1; ... ) infinite loop, 1 is a truthy value.
[last,add] the new pair is the last value of the old pair and the sum of the old pair.
while returns all intermediate pairs, [1] gets the second element of each pair.
jq, 35 33 bytes
A recursive filter written for this tip.
def f:(.<2//[.-1,.-2|f]|add?)//.;
Grok, 16 bytes
1z1j
wYZlYp2yp+9
Prints an infinite, tab-separated sequence. (Tabs instead of spaces/newlines since they are golfier.) The 5 flag is just so it times out faster.
Explanation:
1z # Print the initial 1
1 # Push 1 to the stack
j # Start the IP moving down
l # Start the IP moving right
Yp # Get the last number on the stack
2yp # Get the number before that (initially 0)
+ # Add them together
w 9 # Print a Tab
YZ # Print the next number without popping it
Vyxal, 2 bytes
ÞF
Before you go saying that the online link doesn't match the submission here, that's because the extra , is needed to actually make the output appear online. If you use the offline version, then you will see that the above works just fine. Also, the 5 flag makes sure that the online interpreter times out after 5 seconds.
Explained
ÞF # Push every Fibonacci number
And now for the non-trivial version
Vyxal 5, 6 bytes
⁽+dk≈Ḟ
Once again, discrepancies between online link and actual version are for the purposes of making it work online.
Explained
⁽+dk≈Ḟ
⁽+d # lambda x, y: x + y
k≈ # the list [0, 1]
Ḟ # Create an infinite sequence based on the function and the initial list.
Fun fact: the infinite sequence function you see was inspired by the sequence blocks of the golfing language Arn by ZippyMagician.
Knight, 20 19 bytes
;=x=y 1W!Ox=y+x=x y
-1 byte: W1;Ox -> W!Ox
The "print infinitely" variant. (It will eventually overflow).
It is a simple add and swap loop.
Ungolfed:
# init x and y to 1
; = x (= y 1)
# loop forever
# since OUTPUT evaluates to NULL, we
# can just invert the condition
: WHILE !(OUTPUT x) {
# Add and swap
: = y + x (= x y)
}
Red, 36 bytes
Infinitely outputs the fibonacci sequence. Also see @Razetime's answer for a recursive version which outputs the nth number.
a: b: 1
forever[print a b: a + a: b]
Red, 36 bytes
An alternative 36.
a: 1 b: 0
forever[print b: a + a: b]
C (clang), 79 70 47 46 bytes
y;z;main(x){for(;printf("%i ",z=x+y);y=z)x=y;}
Uses a for-loop instead of a while-loop just because I use it more and doing while() gives the same byte count.
Thanks to ceilingcat for golfing 9 bytes. Thanks to Jo King for golfing 23 bytes. Thanks to ceilingcat for golfing another byte.
Red, 47 bytes
F: func[N][either N < 2[n][(F N - 2)+ F N - 1]]
First red answer. Modified from the solution on this page.
COBOL (GNU), 170 bytes
I am surprised at the lack of COBOL answers on this site. Well, it is ancient after all.
This outputs the fibonacci sequence correctly up to 38 digits.
PROGRAM-ID.H.DATA DIVISION.LOCAL-STORAGE SECTION.
1 a PIC 9(38).
1 b PIC 9(38).
PROCEDURE DIVISION.G.COMPUTE a=0**b+b -a
ADD a TO b
DISPLAY b(38- FUNCTION LOG10(b):)GO G.
Explanation
We just need two variables, a and b to compute the whole fibonacci sequence. Here is pseudocode of what this would look like:
a = 0
b = 1
loop {
a = b - a
b += a
print(a)
}
Translating the pseudocode above in COBOL is relatively short and simple. But we see that variables in COBOL are set to 0 by default, and having one of them set to a 1 is kind of (8 bytes) long, so we hack it out like so:
a = 0
b = 0
loop {
a = b - a + 0 ** b
b += a
print(b)
}
The 0 ** b ensures that a = 1 on the first iteration. From then on, the logic is the same as in our first pseudocode implementation (since 0 ** (any number greater than 0) = 0). The change from print(a) to print(b) is just to ensure that the numbers are outputted in the correct order.
Ungolfed
PROGRAM-ID. H.
DATA DIVISION.
LOCAL-STORAGE SECTION.
1 a PIC 9(38). // Declare a variable named `a` (a = 0)
1 b PIC 9(38). // Declare a variable named `b` (b = 0)
PROCEDURE DIVISION.
G. // Define a label named `G`
COMPUTE a=0**b+b -a // a = b - a + 0 ** b
ADD a TO b // b += a
DISPLAY b(38- FUNCTION LOG10(b):) // Print `b` without trailing zeros
GO G. // Jump to the label named `G` (4 lines above)
Brainfuck, 22 bytes
+>++[-<<[->+>+<<]>>>+]
Generates the Fibonacci sequence gradually moving across the memory tape.
Branch, 18 bytes
1XY[/x#^\yX^+Y10.]
Try it on the online Branch interpreter!
Outputs infinitely. Eventually starts producing garbage values because long long int overflows but that seems to be acceptable.
Explanation
1 Set the node's value to 1
XY Set the X and Y registers to 1
[ ] While value is not 0 (this will always be true in this program)
/x# Move to the left child, set to the X register, and output as number
^\ Move to the parent and then right child (go to right sibling)
yX Set to the Y register, then set the X register to that value
^+Y Move to root, sum the children (X + Y), and set the Y register
10. Place 10 and output as character; this also keeps the loop going
Duocentehexaquinquagesimal, 5 bytes
±∊YO$
Try it online! Link is to a version with output; this one just writes the sequence to memory. Outputs codepoints of the entire sequence. Stops eventually because of memory limitations.
Barrel, 26 bytes
Disclaimer: The language is newer than the question, but I didn't even think of golfing this until after I'd created the language. I did update the language after I originally wrote the answer, and changed my answer, but that was because I was fixing the interpreter and made some changes to the spec to make the language work better. I wasn't cheating, I promise :)
+&1:0¤n &0:@1&1:a#@0+←1
Explanation:
+ // set the accumulator to one by incrementing (initialization)
&1:0 // set register 1 to value 0 (initialization)
¤ ←1 // define a target that can be jumped to; then, jump to the previously defined jump target
n // print the accumulator as a number and implicitly print the following space
&0:@1 // set register 0 to register 1
&1:a // set register 1 to the value of the accumulator
# // for as many times...
@0 // ... as [value of register 0]...
+ // ... increment the accumulator
I find it a bit hard to explain this further, so here's a rough chart of the accumulator and the two registers used during execution which will hopefully remove any confusion:
acc reg[0] reg[1] |
---------------------- |
1 <uninit> 0 | initialize; print acc("1")
1 0 1 | set reg[0] to reg[1]; set reg[1] to acc
1 0 1 | add reg[0] to acc; jump back and print acc ("1")
1 1 1 | set reg[0] to reg[1]; set reg[1] to acc
2 1 1 | add reg[0] to acc; jump back and print acc ("2")
2 1 2 | set reg[0] to reg[1]; set reg[1] to acc
3 1 2 | add reg[0] to acc; jump back and print acc ("3")
3 2 3 | set reg[0] to reg[1]; set reg[1] to acc
5 2 3 | add reg[0] to acc; jump back and print acc ("5")
5 3 5 | set reg[0] to reg[1]; set reg[1] to acc
8 3 5 | add reg[0] to acc; jump back and print acc ("8")
...and so forth and so on.
APL (Dyalog Unicode), 7 bytes
This algorithm is based on Pascal's Triangle, and I take no credit for it. Simply submitting it for completeness.
+.!∘⌽⍨⍳
+.! is the summation of binomial coefficients. In this context k!n can be thought of as the kth element in the nth row of Pascal's Triangle (zero indexed).
∘ is the function composition operator called Beside.
⌽ reverses the array.
⍨ is the commute operator, known as Selfie, it's used to copy the array to the left side of the composed function.
⍳ the index generator creates a range, from 0–(n-1) inclusive.
V (vim), 32 bytes
i1
1<esc>qqkyjGp:s:\n:+
C<C-r>=<C-r>"
<esc>@qq@q
Prints the sequence forever.
Output is not visible on TIO, so here's the first 99 iterations: Try it online!
Last accurate value is \$7540113804746346429\$ after which it exceeds the integer limit.
VBScript, 41 bytes
sub f(x,y):msgbox x:f y,x+y:end sub:f 1,1
Very simple self-explanatory recursive function.
It outputs its first parameters and recursively called again with the second parameter and first+second parameter. And first it is called with 1,1.
1,1 -> 1, f(1,2)
1,2 -> 1, f(2,3)
2,3 -> 2, f(3,5)
and so on
Pxem, Filename: 29 bytes + Content: 0 bytes = 29 bytes.
Outputs fibonacci sequence, separated with space.
- Filename (escaped):
\001.rX\001.w.c.n.c.t.v.m.v.+ .oX.a- Actual:
.rX.w.c.n.c.t.v.m.v.+ .oX.a
- Actual:
- Content: empty.
With comments
XX.z
# push 1; push $(($(pop)*$(rand)))
# NOTE rand pushes 0<=x<1
# NOTE null character cannot be used for filename
.a\001.rXX.z
# push 1; push 88; while [ $(pop) -ne 0 ]; do
.aX\001.wXX.z
# Do I really need to explain more?
# Just read the specification; I am going to bed
# also a sequence .t.v.m.v is an idiom
# to move top item to bottom
.a.c.n.c.t.v.m.v.+ .oX.a
Whispers v3, 35 bytes
> Input
> fₙ
>> 2ᶠ1
>> Output 3
Try it online! (or don't, as this uses features exclusive to v3)
Simply takes the first \$n\$ elements of the infinite list of Fibonacci numbers.
><> - 15 characters
0:nao1v
a+@:n:<o
BRASCA, 13 bytes
After being inactive here for god knows how long, I built a little esolang and decided to put it to the test.
Outputs each number seperated by newline.
nlo1[:n:R+lo]
Explanation
n - Output 0 as number (an empty stack always pops zero)
lo - Push 10 (line feed) to the stack and print it
1 - Push 1 to the stack
[ ] - While not zero:
:n - Output the number
:R+ - Add it with the previous number
lo - And print another line feed
Language Link
convey, 8 bytes
Generates the sequence.
v+"}
1"1
The values (initially 1 and 1) follow the conveyor belts indicated by the arrow heads. " duplicates the input into both outputs, + adds them, and } writes them to the output.
Javascript, 27 26 25 23 characters
for(a=b=1;n--;)a+=b=a-b
In an interactive javascript command line (Like google chrome console) it'll print out the nth fibonacci term for n > 1. undefined for n=1, runs forever for n < 1.
Credit to Bojidar Marinov
41 characters
for(x=[1,1],y=1;n-++y;)x[y]=x[y-1]+x[y-2]
Saving the n (>=2) first terms in an array.
x86 machine code - 15 bytes
This is the easiest way my answer to generate fibonacci numbers. I don't believe using XADD instruction, I can generate fibonacci numbers. Well, output store in eax, debug it using GDB with peda (GDB plugin) to make debugging easier. Just make a breakpoint at fib_seq label then s (mean single-step).
So this is example :
1 global fib_seq
2 section .text
3
4 fib_seq:
5 00000000 31C0 xor eax, eax ; eax = 0
6 00000002 6A01 push 1
7 00000004 5A pop edx ; edx = 1
8 00000005 6A0A push 10
9 00000007 59 pop ecx ; loop counter
10 .loop:
11 00000008 E305 jecxz .exit_loop
12 0000000A 0FC1D0 xadd eax, edx
13 0000000D E2F9 loop .loop
14 .exit_loop:
Rockstar, 121 110 86 82 bytes
1-indexed
listen to N
X's1
Y's1
while N
let Z be X+Y
let X be Y
let Y be Z
let N be-1
say X
Try it here (Code will need to be pasted in)
Arn, 5 bytes
Since I finally implemented sequences in my interpreter this is now a valid submission :)
╔Tò”7
Explained
Unpacked: [1 1{+
[ Sequence...
1 1 ...with 2 values initialized at 1...
{ ...the rest of which are determined by the block...
+ ...that adds the top two values
} Implied, can be removed
] Implied, can be removed
Since Arn supports infinite sequences and BigNums, this will continuously output fibonacci numbers infinitely (hypothetically)
Flurry, 46 bytes
{}{<{}{<[<>{}]{{}[<><<>()>]}>}>}{{}{{}}{{}}}()
How to run:
$ target/Flurry -nin -c "{}{<{}{<[<>{}]{{}[<><<>()>]}>}>}{{}{{}}{{}}}()" 8
34
It doesn't use the stack at all (except for fetching the input number from the pre-populated stack). Instead, it uses pure functional construction developed by Anders Kaseorg in my SKI golf challenge.
one = \f. \x. f x
= I
= {{}}
one-pair = \f.f one one
= {{}{{}}{{}}}
succ = \n. \f. \x. f (n f x)
= \n. \f. S (\x. f) (n f)
= \n. S (\f. S (K f)) n
= S (S . K)
= <><<>()>
next-pair-helper = \f. \m. \n. f n (m succ n)
= \f. \m. S f (m succ)
= \f. S f ∘ (\m. m succ)
= {<[<>{}]{{}[<><<>()>]}>}
next-pair = \p. \f. p (next-pair-helper f)
= \p. p ∘ next-pair-helper
= {<{}{<[<>{}]{{}[<><<>()>]}>}>}
fib = {} next-pair one-pair K
= {}{<{}{<[<>{}]{{}[<><<>()>]}>}>}{{}{{}}{{}}}()
Flurry, 54 bytes
<>{<>(){}(<>())}{{}[<>{<>(){}{}[<><<>()>]}{({})}]{{}}}
This is an anonymous function that takes a number \$n\$ as a Church numeral and pushes \$F_n\$ to the stack as a Church numeral.
It can be tested by invoking the interpreter as follows:
$ ./Flurry -inn -c '<>{<>(){}(<>())}{{}[<>{<>(){}{}[<><<>()>]}{({})}]{{}}}{}' 10
55
Note that this is very slow for large inputs (>30 or so) because Church numeral addition is \$O(n)\$.
Explanation
The basic idea is to loop \$n\$ times and keep track of the smaller number using the stack and the larger number using function parameters, so the function to iterate looks like this:
next = λb. pop() + push(b)
Flurry is mostly combinator-based, and so doesn't really have lambdas. The closest approximation is to write a function that pushes its argument onto the stack (using the {...} monad) and then pops from the stack to read the argument back (using the {} nilad). So the function λx. f x gets represented as:
{ f {} }
However, this translation doesn't work if f depends on the stack, which is true in this case, so we need to use a combinator-based approach instead. Rather than popping using {} directly, we can write an anonymous function that ignores its argument and returns a value popped from the stack:
λa. pop()
{ <> () {} {} }
Here, <> and () represent the S and K combinators respectively.
Of course, the next thing we do with the popped value is apply it to the successor function <><<>()> to compute addition:
λa. pop()(suc)
{ <> () {} {} [<><<>()>] }
Now all we need is to write a function that pushes its argument to the stack and returns it unchanged:
λa. push(a)
{ ({}) }
We can then put these functions together using the S combinator:
λb. pop() + push(b)
λb. S (λb. pop()(suc)) (λb. push(b)) b
<> {<>(){}{}[<><<>()>]} {({})}
The main function is responsible for setting up the initial values and calling next the appropriate number of times. In other words, it looks like this:
main = λn. push(0); n (next) (1)
Since we don't care about the return value, we can just use function application to sequence the two actions:
main = λn. push(0) (n (next) (1))
Again, we can't keep lambda variables on the stack because we're already doing stack manipulation, so we'll have to create intermediate functions. First, one that ignores its argument and pushes 0 to the stack:
λa. push(0)
{ <> () {} (0) }
Second, one that applies its argument to next and 1 (which we can finally use stack lambdas for):
λa. a next 1
{ {} next 1 }
Again, we can put these together with S:
<> {<>(){}(0)} {{}[next]1}
Substituting the definitions of 0, next, and 1 gives us the final result:
<>{<>(){}(<>())}{{}[<>{<>(){}{}[<><<>()>]}{({})}]{{}}}
Javascript, 24 bytes - recursive version, 33 bytes - usage of Binet's formula, 46 bytes - continuous approximation with the "phi" itself
Usage of "Binet's formula" and a bitwise "OR" operator to round the result. Originally in the "Binet's formula" you have to subtract the so-called "smaller phi to the n-th power". "Smaller phi" (-0.618...) is inside the (-1;1) interval, so it gets closer to 0 with each positive power - that's why we can leave it, and just round the meaningful part. Function itself is an anonymous one, declared with the arrow function declaration.
n=>(((5**.5/2+.5)**n)/5**.5)+.5|0
Recursive version - arrow function declaration. Check whether n is less than 3, if so return 1, else do it again (at least) 2 more times, but with an argument of value n-1 and n-2:
f=n=>n<3?1:f(n-1)+f(n-2)
Continuous approximation. Ni * phi = Ni+1.
WARNING - RUNNING THIS CODE WILL END UP AS AN INFINITE AMOUNT OF ALERTS (next after clicking "ok")
f=n=>{l=n/2+5**.5/2*n+.5|0;alert(l);f(l)};f(1)
GAS x86-64 for Linux (Machine code), 76 68 bytes
Loop-free, because I thought it would be a fun idea. GCC 10.1.
Note/warning: for this to work, you have to turn off DEP and PIE (ASLR). See compilation instructions below.
Look, ma! No loops! Byte count is for the assembled opcodes of func + e + f. Works on 32 bit input. Sure, you'll eventually run out of stack space, but the number will overflow before then. Obviously, a loop would have been much smaller (and easier) to write.
How it works:
- Copy payload code to stack-relative space (No modification of
%rsp) - Jump to copy destination's start.
- Payload calculates the Fibonacci number in
%raxand self-unwinds without ever looping - When it's done, return to caller of func
Full testing program:
// 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
.global main
message: .asciz "%d"
main:
mov $N, %rdi
call func
mov %eax, %esi
mov $message, %rdi
xor %eax, %eax
call printf
xor %eax, %eax
ret
func:
// We'll take %rdi, but we'll slice it to 32 bits
// %edi is arg, r8d is our counter.
mov %edi, %r8d
// Make 2 copies for arithmetic
mov %r8d, %eax
// Set up stack offset
// N * 32, need 64 bits to work with %rsp
imul $(eof - e), %eax
neg %rax
mov %rsp, %r9
lea (%rax, %r9), %r9
// Initialize for Fibonacci
xor %ebx, %ebx
xor %eax, %eax
inc %eax
// Copy initial payload:
// Because PIE is turned off, we can use 32-bit addressing for local
// Stack still seems to be in 64-land, however
mov $e, %esi
mov %r9, %rdi
mov $(eof - e), %ecx
rep movsb
// Go to stack offset
jmp *%r9
e:
// The payload:
dec %r8d
jg f
ret
f:
// Do actual Fibonacci stuff
lea (%ebx, %eax), %edx
mov %eax, %ebx
mov %edx, %eax
// Self-replicate
mov %r9, %rsi
mov $(eof - e), %cl
rep movsb
eof:
I decided on 32-bit input because the stack is not all valid for 64 bits, so we'd run out anyway. It overflows after a we get high enough input, but that's expected.
Compilation:
# Prints 55
# Replace 10 with the input number (1-indexed):
gcc -no-pie -z execstack execstack_fibonacci.sx -DN=10 -g
- The
-z execstacktells the linker to turn off DEP for this program. (Allow the stack to be executable) - The
-no-pieturns off ASLR. - The
-DN10is just easy input control. - The
-gis for debugging control. Turn it off if you want.
Note: this will NOT work in MinGW because the DEP policy is managed by the OS on Windows. In fact, -z isn't even recognized by MinGW's ld.
Hex dump:
funcs='func e f'
for el in $funcs; do
echo 'Dump $el'
gdb -batch -ex "disas/r $el" ./a.out | sed '/^$/d'
done
echo -n "payload size:"
gdb -batch -ex "print eof - e" ./a.out
Intel 8087 FPU, 13 bytes
Binary:
00000000: d9e8 d9ee dcc1 d9c9 e2fa df35 c3 ...........5.
Listing:
D9 E8 FLD1 ; push initial 1 into ST(1)
D9 EE FLDZ ; push initial 0 into ST
FIB_LOOP:
DC C1 FADD ST(1), ST ; ST(1) = ST(1) + ST
D9 C9 FXCH ; Exchange ST and ST(1)
E2 FA LOOP FIB_LOOP ; loop until n = 0
DF 35 FBSTP [DI] ; store result as BCD to [DI]
C3 RET ; return to caller
As a callable function, input n in CX, output to a 10 byte little-endian packed BCD representation at [DI]. This will compute up to Fibonacci n=87 using the Intel x87 math-coprocessor using 80-bit extended-precision floating point arithmetic.
Run using DOS DEBUG with n = 9, result 34:
n = 87 (0x57), result 679891637638612258:
R, 33 32 bytes
CAUTION: This attempts to print the whole Fibonacci sequence. It does not stop.
a=b=1;repeat print(a<-(b=b+a)-a)
Pretty simple. Initialize a and b. Then a repeat loop which adds them to find the next number and print it. This loop will not stop, though eventually the overflow means it just prints NaN repeatedly.
Edit: saved 1 byte by switching to a=b=1 which required a different loop control mechanism to print the first few values, and then a different assignment location, etc.
Python 2, 59 51 55 33 bytes
a=0
b=1
while 1:a,b=b,a+b;print a
Thanks for @pppery for saving a whole 22 bytes!
International Phonetic Esoteric Language, 28 bytes
<f>/b1ɨʌʟ|e|1zb1z<f>d<fib>s|e|\
A function that expects a number \$n \ge 0\$ to be on the stack, and leaves the \$n\$-th Fibonacci number.
Explanation:
<f>/ (n1 -- n2) (where n2 is the n1-th fibonacci number)
(check for case n=1)
b (dup)
1 (push 1)
ɨ (n>1?)
ʌ (skip if n>1)
ʟ⟨e⟩ (if n<=1, jump to end label)
1 (push 1)
z (subtract)
b (dup)
1 (push 1)
z (subtract)
<f> (recurse)
d (swap)
<f> (recurse)
s (add)
⟨e⟩ (end label)
\
dc, 21 17 bytes
0z[dp_3R+lmx]dsmx
This prints the Fibonacci sequence endlessly.
My previous (21-byte) version accepted an input \$n\$ on stdin, outputting the \$n^\text{th}\$ Fibonacci number on stdout (1-indexed):
9k5v1+2/?^5v/.5+0k1/p
Go 114 113 106 chars
I'm sure this can be improved but I'd like to share my approach using the closed-form expression to calculate Fibonacci numbers.
package main
import(."fmt"
."math")
func main(){for i:=0.0;i<31;i++{Printf("%.0f\n",Pow(Phi,i)/Sqrt(5));}}
Pyth, 13 bytes
A(Z1)#HA(H+HG
Explanation
A(Z1)#HA(H+HG
(Z1) : The tuple (0, 1)
A : Assign the first value of the tuple to G and the second to H
# : Loop until error statement
H : Print H
(H+HG : The tuple (H, H + G)
A : Assign the first value of the tuple to G and the second to H
Erlang (escript), 36 bytes
I'm a total idiot. I didn't even think of this formula!
f(X)when X<2->1;f(X)->f(X-1)+f(X-2).
Erlang (escript), 50 bytes
f(X,Y)->io:write(X),io:nl(),f(Y,X+Y).
f()->f(1,1).
Erlang (escript), 51 bytes
Tail-recursion optimized.
f(0,X,_)->X;f(I,X,Y)->f(I-1,Y,X+Y).
f(X)->f(X,1,1).
JVM Byte Code, 79 bytes
The byte count given is for a complete class file that defines a class Code containing single static method Code which implement Fibonacci. A hex dump of the file is given below.
0000000: cafe babe 0003 002d 0004 0100 0428 4929 .......-.....(I)
0000010: 4901 0004 436f 6465 0700 0200 2000 0300 I...Code.... ...
0000020: 0000 0000 0000 0100 0800 0200 0100 0100 ................
0000030: 0200 0000 1800 0400 0100 0000 0c03 045a ...............Z
0000040: 6084 00ff 1a9d fffa ac00 0000 0000 00 `..............
A helper class is required to invoke the function.
class Test {
public static void main(String[] args){
for(int i = 0; i < 20; i++){
System.out.println(Code.Code(i));
}
}
}
The disassembly of the class file with javap -c shows actual byte code implementation of Fibonacci. This requires only 11 bytes, the rest of the 79 bytes in the class file are various header tables that can't be omitted.
class Code {
static int Code(int);
Code:
0: iconst_0
1: iconst_1
2: dup_x1
3: iadd
4: iinc 0, -1
7: iload_0
8: ifgt 2
11: ireturn
}
Taktentus, 87 bytes
a:=1
@wy_n:=a
@wy:=32
b:=1
n:=44
@>=n
_:=@stop
@wy_n:=a
@wy:=32
c:=a
a+=b
b:=c
n--
_-=8
n are variable how many times we count (n-1 because first are writing directly)
tq, 6 bytes
Currently this has no separator...
01p+r)
Explanation
0, # Initialize the number 0
1, # (Since a preceding 0 in decimal is disallowed)
p+r, # Initialize the third item in the list as the
# previous item + the previous-previous item
) # Extend this forever
Gol><>, 7 bytes
12K+:N!
Byte knocked off courtesy of JoKing
9 bytes
01T2K+:Nt
Outputs forever with newlines
Java, 90 characters and just two variables
There was one before with 55 characters, but it used a variable without declaring it and had no output. This one has both and (the actual logic) is shorter. And as a little bonus it looks absolutely horrific code-style-wise and depends on compiler quirks, yay!
interface A{static void main(String[]x){for(int a,b=a=1;;System.out.println(b=a+(a=b)));}}
The special features I used are:
- Using an interface instead of a class. The program can still be run as normal, but I don't need to write "
public" twice. This saves 10 characters - Declaring multiple variables at once:
int a,b; - Initializing multiple variables at once and in the declaration, needs a second
a:b=a=1; - Everything is done in the
forhead, the body is empty:for(...);
The first and third block offorare intended for variable initialization and variable incrementation, but they can hold any commands. - The whole logic is inside the output:
System.out.println(b=a+(a=b)) - Just two variables without recursion! This is done by using the way the compiler works: The assignment to
bfirst reads the value ofa, then it evaluates the right side of the+, where it reads the value ofband writes it intoa, but the left side of the+still has the old value ofathat gets added to the value ofbafter assigning the value ofbtoa. Then that sum gets written tobwhileaalready holds the old value ofb.
I was lucky that the compiler works this way, because it could also have first evaluated the expression in the brackets, like for example C does, then it just lists all powers of 2 instead of the Fibonacci numbers.
In a dream programming language this would just be: b=a+(a=b
Cascade, 28 25 bytes
?01
^/
|.#
!9]
-0
!0]
+1
Outputs the Fibonacci numbers separated by tabs starting from 1. This shows off the behaviour of variables in Cascade, in that the variables 1 and 0 aren't static in this program.
Unfolded, this looks something like:
@
^
^ \
/ . |
# 9 |
] |
0 - |
] 0 |
1 + /
1 0 /
|
This initially branches twice, with the leftmost going down the tree until it sets ([) the variable 1 to the sum (+) of 1 and 0. Then it sets 0 to that value to the result of that minus 0. This has the effect of advancing one element in the Fibonacci sequence.For example, the values of repeated executions are:
0 1
1 1
1 2
2 3
3 5
5 8
8 13
...
Finally it prints the total result of that, which is the new value of 0. The next branch prints the tab separator (.9), and the final branch loops back around to the top of the program.
Oasis, 2 bytes
Answer to the open exercise on the Oasis repo.
+T
Explanation
Expanded program:
bc+10
When + requires 1 parameter, it tries to calculate a(n-1). For the other parameter, it tries to calculate a(n-2). (Hence the expansion.)
In addition, the T instruction expands to 10 in the program, which are the base test cases (a(0) is 0. a(1) is 1. Since base test cases are popped from the end before the Oasis program is executed in reverse.)
Brain-Flak, 36 34 32 bytes
({}(())){({}[()]<(({})<>{})>)}<>
Outputs the nth number of the zero indexed Fibonacci sequence (F(0) = 1, F(1) = 1, etc.)
Explanation coming soon...
Zsh, 31 bytes
for ((a=1;b+=a;a+=b))echo $a $b
32 bytes, based on James Brown's awk solution:
for ((y=1;z=x+y;y=z))echo $[x=y]
42 bytes, to halt before int overflow:
(for ((a=1;b+=a;a+=b))echo $a $b)|head -46
NB: For a properly "endless" solution I need logic for long long (..) long integers, per this post
8086/8088 machine code, 8 bytes
The machine code is on the left; the middle column is disassembly and the rightmost column is an explanation.
40 ; inc ax set ax to 1
41 ; inc cx set cx to 1
ef ; out [dx], ax output ax to port [dx] (that is, port 0)
03 c1 ; add ax, cx set ax to ax + cx
91 ; xchg ax, cx exchange ax with cx
eb fa ; jmp -4 jump to "out [dx], ax"
Assumptions:
- The registers AX, CX and DX are initially 0.
- A number may be output by writing it as a word to port 0.
This runs forever, outputting the Fibonacci numbers modulo \$2^{16}\$ = 65,536, starting with 1, 1.
pure bash, 43 chars
Inspired from user unknown's answer:
for((r=l=i=1;i++<40;l+=r+=l)){ echo $r $l;}
Not really golfed, but I like it anyway.
Or
r=1 l=0;echo {,,}{,,}{,,}\ $[r+=l]\ $[l+=r]
Flobnar, 19 bytes
@\
#_+_1
!_:.
9>$!,
Generates the sequence with no end, separating each number with a tab.
One year later...
I should probably check if I've already answered a question before I start coding...
Anyway, here's an alternative 19 byter that outputs in the same way, only 1-indexed this time and without the leading tab.
Flobnar, 19 bytes
!\$\@
:>+_,9
+ <>$.
Golfscript 42 bytes
~:n;2 -1?:h;5h?:f;1f+2/:p;p n?-1p*n~)?-f/
I origionally solved this in python with 64chars because i didn't think golfscript supported floats. I did some more digging and it actually does if you raise a number to -1.
Back in my graph theory/combinitorics class we went over creating an O(1) form of recurance eqautions, the fibonacci sequence is one example we used. I don't remeber the method for converting a recurance equation to constant time because the class was a few years ago, but I found the solution for the fibonacci equation online
This allows you to compute the nth fibbonacci number without computing the previous terms
Jasmin, 120 bytes
Defines a class F with a static method f that calculates the nth Fibonacci number. My implementation is essentially an iterative solution that stores partially computed Fibonacci numbers on the stack.
.class F
.super java/io/File
.method static f(I)I
ldc 0
ldc 1
dup_x1
iadd
iinc 0 -1
iload_0
ifgt $-9
ireturn
.end method
Some interesting golfing tricks used
- Extending
java/io/Fileis shorter than extendingjava/lang/Object(The super line cannot be omitted). I've check andFileis tied for the shortest fully qualified class name. - Making this an instance method would let me remove
staticfrom the method header but, then I would have to explicitly implement an empty constructor to make the function callable (costing quite a few bytes). - Juggling the Fibonacci values on the stack turned out to be shorter than storing them in local variables.
- On the other hand it's worth storing the index in a local variable. This makes stack management easier (i.e. shorter) without too much extra length since there is an instruction for adding or subtracting from locals variables.
- Although the JVM technically requires that you declare the maximum stack size before hand with
.limit stack 5, this can be omitted if the class file is executed with the-noverifyflag. I'm pretty sure this is some sort of undefined behavior but, it works in this this case.
Test setup
To test the code you, need a main method to invoke the static method.
class FibTest {
public static void main(String[] args){
for(int i = 0; i < 20; i++){
System.out.println(F.f(i));
}
}
}
You then need to use jasmin.jar (obtained from the source forge linked in the title) to build F.class before building and executing the test file. Since the stack size was omitted, you need to execute the class with -noverify. The makefile below handles this.
test: FibTest.class
java -noverify FibTest
FibTest.class: FibTest.java F.class
javac FibTest.java
F.class: F.j
java -jar jasmin.jar F.j
bash pur, 49 chars, third solution
r=0;l=1;echo -e {1..45}" $((r+=l)) $((l+=r))\n";
bash pur, 52 chars, second solution
r=0;l=1;echo -e {1..40}" "$((r+=l))" "$((l+=r))\\n;
former solution (60 chars):
r=0;l=1;for i in {1..40};do((r+=l));((l+=r));echo $r $l;done
x86 Machine Code (ELF format) - 484 bytes
This program will calculate fibonacci digits until there is no memory left, so you might want to process the output to get Nth one you are looking for.
Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
00000000 7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 .ELF............
00000010 02 00 03 00 01 00 00 00 C0 80 04 08 34 00 00 00 ........Ŕ€..4...
00000020 00 00 00 00 00 00 00 00 34 00 20 00 02 00 28 00 ........4. ...(.
00000030 00 00 00 00 01 00 00 00 00 00 00 00 00 80 04 08 .............€..
00000040 00 00 00 00 E4 01 00 00 00 10 00 00 05 00 00 00 ....ä...........
00000050 00 10 00 00 01 00 00 00 00 00 00 00 00 90 04 08 ................
00000060 00 00 00 00 00 00 00 00 00 00 10 00 06 00 00 00 ................
00000070 00 10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
00000080 51 B9 00 90 04 08 88 01 31 C0 BA 01 00 00 00 EB Qą......1Ŕş....ë
00000090 03 51 89 C1 31 C0 89 C3 43 B0 04 CD 80 31 C0 99 .Q‰Á1Ŕ‰ĂC°.Í€1Ŕ™
000000A0 42 59 C3 00 00 00 00 00 00 00 00 00 00 00 00 00 BYĂ.............
000000B0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
000000C0 31 C0 99 42 B9 03 90 04 08 C6 41 01 0A C6 41 02 1Ŕ™Bą....ĆA..ĆA.
000000D0 01 C6 41 03 01 3A 71 03 0F 84 FF 00 00 00 3A 71 .ĆA..:q..„˙...:q
000000E0 03 74 26 80 41 03 05 0F B6 41 03 6B C0 08 00 41 .t&€A...¶A.kŔ..A
000000F0 04 8A 41 04 E8 87 FF FF FF 80 69 04 30 C6 41 03 .ŠA.č‡˙˙˙€i.0ĆA.
00000100 01 83 E9 03 3A 71 03 75 DA 8A 41 04 E8 6F FF FF ..é.:q.uÚŠA.čo˙˙
00000110 FF 3A 71 06 0F 84 BA 00 00 00 0F B6 41 05 88 41 ˙:q..„ş....¶A..A
00000120 06 0F B6 41 07 88 41 05 0F B6 41 07 00 41 06 C6 ..¶A..A..¶A..A.Ć
00000130 41 07 00 3A 71 06 0F 84 88 00 00 00 C6 41 07 01 A..:q..„....ĆA..
00000140 FE 49 06 3A 71 06 0F 84 78 00 00 00 C6 41 07 02 ţI.:q..„x...ĆA..
00000150 FE 49 06 3A 71 06 0F 84 68 00 00 00 C6 41 07 03 ţI.:q..„h...ĆA..
00000160 FE 49 06 3A 71 06 0F 84 58 00 00 00 C6 41 07 04 ţI.:q..„X...ĆA..
00000170 FE 49 06 3A 71 06 74 4C C6 41 07 05 FE 49 06 3A ţI.:q.tLĆA..ţI.:
00000180 71 06 74 40 C6 41 07 06 FE 49 06 3A 71 06 74 34 q.t@ĆA..ţI.:q.t4
00000190 C6 41 07 07 FE 49 06 3A 71 06 74 28 C6 41 07 08 ĆA..ţI.:q.t(ĆA..
000001A0 FE 49 06 3A 71 06 74 1C C6 41 07 09 FE 49 06 3A ţI.:q.t.ĆA..ţI.:
000001B0 71 06 74 10 FE 41 08 FE 41 09 FE 49 06 0F B6 41 q.t.ţA.ţA.ţI..¶A
000001C0 06 88 41 07 C6 41 06 01 83 C1 03 3A 71 06 0F 85 ..A.ĆA...Á.:q..…
000001D0 46 FF FF FF 3A 71 03 0F 85 01 FF FF FF B3 00 31 F˙˙˙:q..….˙˙˙ł.1
000001E0 C0 40 CD 80 Ŕ@Í€
Keg, 10 bytes
01{:. ,:"+
Endlessly outputs numbers separated by spaces
How it works
0 Pushes 0
1 Pushes 1
{ Begins an endless while loop
:. Outputs the top item of the stack
, Outputs a space
:" Duplicates the top item of the stack and puts it at the bottom
+ Adds the top two numbers of the stack
BitCycle, 17 16 bytes
~1~ +
AB~/!
^ +/
Outputs the 0 based sequence. This could be 14 bytes:
~1~+
AB~!
^ +/
But it prints an extra 0 in front of the sequence, which takes a couple of bytes to fix...
There's also a 17 byte solution:
v0<
AB~
~ +\
~ !
Which I like because you can switch between 0-based and 1-based just by changing the 0 on the first line to a 1.
For both solutions, the numbers are infinitely output is in unary 1 bits separated by 0 bits. The -u flag converts the unary numbers to decimal instead, but the TIO tends to cut off the outputting section sometimes, and the last number is always truncated too. There's a bit in the footer to prevent this.
Explanation:
Basically, these solutions only use a single pair of collectors and distinguishes between the two numbers by storing one as unary 1 bits and the other as unary 0 bits.
This starts off with 1 being pushed to the collectors to initialise the sequence.
~ ~ Invert the whole stack
AB~ This basically swaps the values of the two numbers
Also duplicate a copy downwards and rightwards
Split the stream into zeroes and ones with the plus
! /! Print a single 0 as the separator
^ +/ And add a copy of the 1s to the collector
~ +
! Print a copy of the 1s to the output
This repeats infinitely, basically executing the pseudocode:
a=0
b=1
while 1:
oldA = a
b,a = a,b
print ','
a += oldA
print oldA
Pyramid Scheme, 385 bytes
^ ^
/ \ /l\
/set\ /oop\
^-----^ ^-----^
- ^- /]\ ^-^
^- ^---^ ^- -^
^- ^- -/ \ -^
^- -^ /set\ -^
/[\ / \ ^-----^ -^
^---^ /out\- ^- / \
-^ -^ ^-----^ /+\ /set\
/1\ / \- /x\ ^---^-----^
---/set\ --- - /x\ /+\
^-----^ --- ^---^
/x\ /1\ /x\ -
--- --- ---
This guy's a whopper. Prints terms indefinitely with no separator. The bit on the left initializes the blank variable and x to one, and the bit on the right does the Fibonaccing. The loop condition (everything to the left below loop) prints both variables before checking the blank one for truthiness (it'll always be nonzero). The loop body updates first blank and then x, thus generating the next two terms for the condition to print.
I can't quite figure out set. It doesn't quite follow the chain of execution, but it almost does, I think. I'll be looking at the Pyramid Scheme source in the next few days (and possibly extending the language); perhaps this will provide me with the insight required to golf some bytes off this monstrosity.
\/\/>, 9 bytes
:@+1}:nau
Outputs infinitely starting from 0, with each number on a new line.
Explanation:
: Dupe top of stack
@ Rotate the top three elements
+ Add the top two elements
1} Push a 1 to the bottom of the stack
:nau Print the top number with a trailing newline
Ouroboros, 10 bytes
Outputs an infinite Fibonacci sequence, starting at 0, separated by newlines.
.!+.@.nao+
Explanation
Each line of an Ouroboros program represents a snake eating its own tail. When execution reaches the end of the line, it loops back to the beginning. Each snake has a stack to store values.
If this is the first pass through the code, we need to initialize the stack by turning the top into a 1. (The empty stack is treated as containing infinite zeros.) .! dups and logically negates (1 if the value was 0, otherwise 0), and + adds that result to the top value. This has the effect of pushing a 1 if the stack was empty, and doing nothing if the stack contained a nonzero value.
Now, call the two numbers on the stack x and y, where x is smaller and y is on the top of the stack. .@.n copies y, rotates x to the top, and outputs a copy of it. a pushes 10 and o outputs it as a character (printing a newline). Finally, + adds x to a copy of y. The stack now contains y and x+y, and we proceed to the next iteration.
Try it out
// Define Stack class
function Stack() {
this.stack = [];
this.length = 0;
}
Stack.prototype.push = function(item) {
this.stack.push(item);
this.length++;
}
Stack.prototype.pop = function() {
var result = 0;
if (this.length > 0) {
result = this.stack.pop();
this.length--;
}
return result;
}
Stack.prototype.top = function() {
var result = 0;
if (this.length > 0) {
result = this.stack[this.length - 1];
}
return result;
}
Stack.prototype.toString = function() {
return "" + this.stack;
}
// Define Snake class
function Snake(code) {
this.code = code;
this.length = this.code.length;
this.ip = 0;
this.ownStack = new Stack();
this.currStack = this.ownStack;
this.alive = true;
this.wait = 0;
this.partialString = this.partialNumber = null;
}
Snake.prototype.step = function() {
if (!this.alive) {
return null;
}
if (this.wait > 0) {
this.wait--;
return null;
}
var instruction = this.code.charAt(this.ip);
var output = null;
console.log("Executing instruction " + instruction);
if (this.partialString !== null) {
// We're in the middle of a double-quoted string
if (instruction == '"') {
// Close the string and push its character codes in reverse order
for (var i = this.partialString.length - 1; i >= 0; i--) {
this.currStack.push(this.partialString.charCodeAt(i));
}
this.partialString = null;
} else {
this.partialString += instruction;
}
} else if (instruction == '"') {
this.partialString = "";
} else if ("0" <= instruction && instruction <= "9") {
if (this.partialNumber !== null) {
this.partialNumber = this.partialNumber + instruction; // NB: concatenation!
} else {
this.partialNumber = instruction;
}
next = this.code.charAt((this.ip + 1) % this.length);
if (next < "0" || "9" < next) {
// Next instruction is non-numeric, so end number and push it
this.currStack.push(+this.partialNumber);
this.partialNumber = null;
}
} else if ("a" <= instruction && instruction <= "f") {
// a-f push numbers 10 through 15
var value = instruction.charCodeAt(0) - 87;
this.currStack.push(value);
} else if (instruction == "$") {
// Toggle the current stack
if (this.currStack === this.ownStack) {
this.currStack = this.program.sharedStack;
} else {
this.currStack = this.ownStack;
}
} else if (instruction == "s") {
this.currStack = this.ownStack;
} else if (instruction == "S") {
this.currStack = this.program.sharedStack;
} else if (instruction == "l") {
this.currStack.push(this.ownStack.length);
} else if (instruction == "L") {
this.currStack.push(this.program.sharedStack.length);
} else if (instruction == ".") {
var item = this.currStack.pop();
this.currStack.push(item);
this.currStack.push(item);
} else if (instruction == "m") {
var item = this.ownStack.pop();
this.program.sharedStack.push(item);
} else if (instruction == "M") {
var item = this.program.sharedStack.pop();
this.ownStack.push(item);
} else if (instruction == "y") {
var item = this.ownStack.top();
this.program.sharedStack.push(item);
} else if (instruction == "Y") {
var item = this.program.sharedStack.top();
this.ownStack.push(item);
} else if (instruction == "\\") {
var top = this.currStack.pop();
var next = this.currStack.pop()
this.currStack.push(top);
this.currStack.push(next);
} else if (instruction == "@") {
var c = this.currStack.pop();
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(b);
this.currStack.push(c);
this.currStack.push(a);
} else if (instruction == ";") {
this.currStack.pop();
} else if (instruction == "+") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a + b);
} else if (instruction == "-") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a - b);
} else if (instruction == "*") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a * b);
} else if (instruction == "/") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a / b);
} else if (instruction == "%") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(a % b);
} else if (instruction == "_") {
this.currStack.push(-this.currStack.pop());
} else if (instruction == "I") {
var value = this.currStack.pop();
if (value < 0) {
this.currStack.push(Math.ceil(value));
} else {
this.currStack.push(Math.floor(value));
}
} else if (instruction == ">") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(+(a > b));
} else if (instruction == "<") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(+(a < b));
} else if (instruction == "=") {
var b = this.currStack.pop();
var a = this.currStack.pop();
this.currStack.push(+(a == b));
} else if (instruction == "!") {
this.currStack.push(+ !this.currStack.pop());
} else if (instruction == "?") {
this.currStack.push(Math.random());
} else if (instruction == "n") {
output = "" + this.currStack.pop();
} else if (instruction == "o") {
output = String.fromCharCode(this.currStack.pop());
} else if (instruction == "r") {
var input = this.program.io.getNumber();
this.currStack.push(input);
} else if (instruction == "i") {
var input = this.program.io.getChar();
this.currStack.push(input);
} else if (instruction == "(") {
this.length -= Math.floor(this.currStack.pop());
this.length = Math.max(this.length, 0);
} else if (instruction == ")") {
this.length += Math.floor(this.currStack.pop());
this.length = Math.min(this.length, this.code.length);
} else if (instruction == "w") {
this.wait = this.currStack.pop();
}
// Any unrecognized character is a no-op
if (this.ip >= this.length) {
// We've swallowed the IP, so this snake dies
this.alive = false;
this.program.snakesLiving--;
} else {
// Increment IP and loop if appropriate
this.ip = (this.ip + 1) % this.length;
}
return output;
}
Snake.prototype.getHighlightedCode = function() {
var result = "";
for (var i = 0; i < this.code.length; i++) {
if (i == this.length) {
result += '<span class="swallowedCode">';
}
if (i == this.ip) {
if (this.wait > 0) {
result += '<span class="nextActiveToken">';
} else {
result += '<span class="activeToken">';
}
result += escapeEntities(this.code.charAt(i)) + '</span>';
} else {
result += escapeEntities(this.code.charAt(i));
}
}
if (this.length < this.code.length) {
result += '</span>';
}
return result;
}
// Define Program class
function Program(source, speed, io) {
this.sharedStack = new Stack();
this.snakes = source.split(/\r?\n/).map(function(snakeCode) {
var snake = new Snake(snakeCode);
snake.program = this;
snake.sharedStack = this.sharedStack;
return snake;
}.bind(this));
this.snakesLiving = this.snakes.length;
this.io = io;
this.speed = speed || 10;
this.halting = false;
}
Program.prototype.run = function() {
this.step();
if (this.snakesLiving) {
this.timeout = window.setTimeout(this.run.bind(this), 1000 / this.speed);
}
}
Program.prototype.step = function() {
for (var s = 0; s < this.snakes.length; s++) {
var output = this.snakes[s].step();
if (output) {
this.io.print(output);
}
}
this.io.displaySource(this.snakes.map(function (snake) {
return snake.getHighlightedCode();
}).join("<br>"));
}
Program.prototype.halt = function() {
window.clearTimeout(this.timeout);
}
var ioFunctions = {
print: function (item) {
var stdout = document.getElementById('stdout');
stdout.value += "" + item;
},
getChar: function () {
if (inputData) {
var inputChar = inputData[0];
inputData = inputData.slice(1);
result = inputChar.charCodeAt(0);
} else {
result = -1;
}
var stdinDisplay = document.getElementById('stdin-display');
stdinDisplay.innerHTML = escapeEntities(inputData);
return result;
},
getNumber: function () {
while (inputData && (inputData[0] < "0" || "9" < inputData[0])) {
inputData = inputData.slice(1);
}
if (inputData) {
var inputNumber = inputData.match(/\d+/)[0];
inputData = inputData.slice(inputNumber.length);
result = +inputNumber;
} else {
result = -1;
}
var stdinDisplay = document.getElementById('stdin-display');
stdinDisplay.innerHTML = escapeEntities(inputData);
return result;
},
displaySource: function (formattedCode) {
var sourceDisplay = document.getElementById('source-display');
sourceDisplay.innerHTML = formattedCode;
}
};
var program = null;
var inputData = null;
function showEditor() {
var source = document.getElementById('source'),
sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
stdin = document.getElementById('stdin'),
stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');
source.style.display = "block";
stdin.style.display = "block";
sourceDisplayWrapper.style.display = "none";
stdinDisplayWrapper.style.display = "none";
source.focus();
}
function hideEditor() {
var source = document.getElementById('source'),
sourceDisplay = document.getElementById('source-display'),
sourceDisplayWrapper = document.getElementById('source-display-wrapper'),
stdin = document.getElementById('stdin'),
stdinDisplay = document.getElementById('stdin-display'),
stdinDisplayWrapper = document.getElementById('stdin-display-wrapper');
source.style.display = "none";
stdin.style.display = "none";
sourceDisplayWrapper.style.display = "block";
stdinDisplayWrapper.style.display = "block";
var sourceHeight = getComputedStyle(source).height,
stdinHeight = getComputedStyle(stdin).height;
sourceDisplayWrapper.style.minHeight = sourceHeight;
sourceDisplayWrapper.style.maxHeight = sourceHeight;
stdinDisplayWrapper.style.minHeight = stdinHeight;
stdinDisplayWrapper.style.maxHeight = stdinHeight;
sourceDisplay.textContent = source.value;
stdinDisplay.textContent = stdin.value;
}
function escapeEntities(input) {
return input.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
function resetProgram() {
var stdout = document.getElementById('stdout');
stdout.value = null;
if (program !== null) {
program.halt();
}
program = null;
inputData = null;
showEditor();
}
function initProgram() {
var source = document.getElementById('source'),
stepsPerSecond = document.getElementById('steps-per-second'),
stdin = document.getElementById('stdin');
program = new Program(source.value, +stepsPerSecond.innerHTML, ioFunctions);
hideEditor();
inputData = stdin.value;
}
function runBtnClick() {
if (program === null || program.snakesLiving == 0) {
resetProgram();
initProgram();
} else {
program.halt();
var stepsPerSecond = document.getElementById('steps-per-second');
program.speed = +stepsPerSecond.innerHTML;
}
program.run();
}
function stepBtnClick() {
if (program === null) {
initProgram();
} else {
program.halt();
}
program.step();
}
function sourceDisplayClick() {
resetProgram();
}
.container {
width: 100%;
}
.so-box {
font-family:'Helvetica Neue', Arial, sans-serif;
font-weight: bold;
color: #fff;
text-align: center;
padding: .3em .7em;
font-size: 1em;
line-height: 1.1;
border: 1px solid #c47b07;
-webkit-box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
background: #f88912;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3), 0 2px 0 rgba(255, 255, 255, 0.15) inset;
}
.control {
display: inline-block;
border-radius: 6px;
float: left;
margin-right: 25px;
cursor: pointer;
}
.option {
padding: 10px 20px;
margin-right: 25px;
float: left;
}
h1 {
text-align: center;
font-family: Georgia, 'Times New Roman', serif;
}
a {
text-decoration: none;
}
input, textarea {
box-sizing: border-box;
}
textarea {
display: block;
white-space: pre;
overflow: auto;
height: 100px;
width: 100%;
max-width: 100%;
min-height: 25px;
}
span[contenteditable] {
padding: 2px 6px;
background: #cc7801;
color: #fff;
}
#stdout-container, #stdin-container {
height: auto;
padding: 6px 0;
}
#reset {
float: right;
}
#source-display-wrapper , #stdin-display-wrapper{
display: none;
width: 100%;
height: 100%;
overflow: auto;
border: 1px solid black;
box-sizing: border-box;
}
#source-display , #stdin-display{
font-family: monospace;
white-space: pre;
padding: 2px;
}
.activeToken {
background: #f93;
}
.nextActiveToken {
background: #bbb;
}
.swallowedCode{
color: #999;
}
.clearfix:after {
content:".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
.clearfix {
display: inline-block;
}
* html .clearfix {
height: 1%;
}
.clearfix {
display: block;
}
<!--
Designed and written 2015 by D. Loscutoff
Much of the HTML and CSS was taken from this Befunge interpreter by Ingo Bürk: http://codegolf.stackexchange.com/a/40331/16766
-->
<div class="container">
<textarea id="source" placeholder="Enter your program here" wrap="off">.!+.@.nao+</textarea>
<div id="source-display-wrapper" onclick="sourceDisplayClick()"><div id="source-display"></div></div></div><div id="stdin-container" class="container">
<textarea id="stdin" placeholder="Input" wrap="off"></textarea>
<div id="stdin-display-wrapper" onclick="stdinDisplayClick()"><div id="stdin-display"></div></div></div><div id="controls-container" class="container clearfix"><input type="button" id="run" class="control so-box" value="Run" onclick="runBtnClick()" /><input type="button" id="pause" class="control so-box" value="Pause" onclick="program.halt()" /><input type="button" id="step" class="control so-box" value="Step" onclick="stepBtnClick()" /><input type="button" id="reset" class="control so-box" value="Reset" onclick="resetProgram()" /></div><div id="stdout-container" class="container"><textarea id="stdout" placeholder="Output" wrap="off" readonly></textarea></div><div id="options-container" class="container"><div class="option so-box">Steps per Second:
<span id="steps-per-second" contenteditable>20</span></div></div>
Python 3, 37 bytes
lambda p,a=5**.5:round((.5+a/2)**p/a)
Explanation
Fib(n) = Fib(n-1) + Fib(n-2) with Fib(0) = Fib(1) = 1
Using some simplification, this becomes:
For n > 0, this becomes
Where round is a function that rounds to the nearest integer.
lambda p, # defines the anonymous function
a=5**.5: # sets a to \sqrt{5}
round((.5+a/2)**p/a) # Runs the function and returns the result
BitCycle, 21 bytes
1+ ~!
CB0CA~
^ 1 <
Outputs an unending sequence. Use the -u flag to get output in decimal. Try it online!
Note: the current BitCycle interpreter doesn't play very well with infinite output. You have to halt the program (Ctrl-C) before it displays anything. On TIO, letting the program run until the 60-second timeout shows no output, either--you have to click the Run button (or hit Ctrl-Enter) again to halt it.
Explanation
This explanation assumes you're familiar with BitCycle.
Conceptually, we store two numbers at a time, the smaller and the larger. At each step, we output the larger, set the new larger to be the larger plus the smaller, and set the new smaller to be the larger.
We store and output the numbers in unary (using 1 bits), but we also need a separator (0 bit) after each number output. Our approach is to store the separator at the end of each number. When adding two numbers, we discard the separator from the first number added, and keep the separator from the second number added.
In the code, the leftmost C collector holds the smaller number, while the rightmost C collector holds the larger. We're actually going to store everything negated, so the numbers are made of 0 bits and the separators are 1 bits. Thus, the leftmost C initially gets a single 1 (unary zero plus a separator bit) and the rightmost C gets 01 (unary one plus a separator bit).
The C collectors open and dump their contents straight into the B and A collectors.
Next, the A collector opens, holding the larger number. It goes through a couple of dupneg devices, with the following results:
- A copy goes into the leftmost
Ccollector, becoming the new smaller number. - A negated copy goes into the sink
!and is output. - A doubly-negated copy goes into the rightmost
Ccollector, but the+ensures that it's only the0bits, not the trailing1separator.
Finally, the B collector opens and dumps its contents into the rightmost C, adding the former smaller number to the former larger number to create the new larger number. The cycle repeats forever.
Other versions
Here's a modified version (still 21 bytes) that strips the separator off the smaller number (instead of the larger) before adding:
10>v ~!
BA+BA~
^ <
And here's an 18-byte version that starts at 0 instead of 1. (Thanks to Jo King for golfing it down from 21 bytes.) Here, we start with the "smaller" number at 1 and the "larger" number at 0, generating the extended Fibonacci sequence 1,0,1,1,2,3,... (Since the "larger" number is what we output, we don't see the first 1.)
1+ ~!
CBCA~
^10 <
Alchemist, 104 87 bytes
-10 bytes thanks to ASCII-only!
_->b+c+m
m+b->m+a+d
m+0b->n
n+c->n+b+d
n+0c->Out_a+Out_" "+o
o+d->o+c
o+0d+a->o
o+0a->m
Produces infinitely many Fibonacci numbers, try it online!
Ungolfed
_ -> b + c + s0
# a,d <- b
s0 + b -> s0 + a + d
s0 + 0b -> s1
# b,d <- c
s1 + c -> s1 + b + d
s1 + 0c -> Out_a + Out_" " + s2
# c <- d & clear a
s2 + d -> s2 + c
s2 + 0d+ a -> s2
s2 + 0a -> s0
Brainfuck, 16,15, 14/13 chars
+[[->+>+<<]>]
Generates the Fibonacci sequence and does not print out anything. Also, is shorter than the one above.
+[.[->+>+<<]>]
This one has 14 characters but prints out ASCII characters with the the values of the Fibonacci sequence.
Alchemist, 68 bytes
y+_->y+a+b
y+0_->z
z+a->z+_
z+0a->x
x+b->x+a
x+0b->y+Out_a+Out_" "!y
Outputs the 1-based sequence infinitely, If you want 0-based (i.e. 0 1 1 2 3 5...), you can change the trailing y to either x or z.
Explanation:
!y # Initialise the program with the y flag alongside the default _
y+_->y+a+b # Convert all _ atoms to a and b atoms
y+0_->z # Once we're out of _ atoms, change to the z flag
z+a->z+_ # Convert the a atoms back to _ atoms
z+0a->x # Switch to the x flag
x+b->x+a # Convert all b atoms to a atoms
x+0b->y # Once we're out, change to y flag
+Out_a # Print the number of a atoms
+Out_" " # And a separator
If it makes you feel better, here's a more pseudo-codey version:
_=1
while true:
a=a+_
b=_
_=a
a=b
print a
C++, 42 bytes
I haven't read every solution in this challenge, but the leaderboard doesn't have a C++ solution, which is a travesty.
int f(int i){return i-->1?f(i)+f(i-1):!i;}
C# (.NET Core), 68, 56 bytes
Lambda using decimal size for single n.
EDIT: Ty Jo King for pointing out better ways to assign the maths to the vars!
p=>{decimal a=0,b=1,j=0;for(;j++<p;b=a-b)a+=b;return a;}
Symbolic Python, 34 31 bytes
-3 bytes thanks to H.PWiz!
__('__=_/_;'+'_,_=_+__,__;_'*_)
Returns the nth element of the Fibonacci, 1-indexed, starting from 1,1,2,3,5....
Explanation:
__( ) # Eval as Python code
'__=_/_;' # Set __ to 1
+' '*_ # Then repeat input times
_,_=_+__,__; # On the first iteration, set _ to __ (1)
;_ # On future iterations, prepend a _
__,_=_+__,__; # Set __ to the next fibonacci number
# And set _ to the old value of __
# Implicitly output _
Or, H.PWiz's version:
__('_=__=_/'+'_;__,_=_+__,_'*_)
Explanation:
__('_=__=_/'+'_;__,_=_+__,_'*_)
__( ) # Eval as Python code
'_=__=_/'+'_; # Set both _ and __ to 1
' '*_ # Repeat input times
__,_=_+__,__ # Set __ to the next fibonacci number
# And set _ to the old value of __
__,_=_+__,_ # Except on the last iteration
# Implicitly output _
R, 37 bytes
Prints the n'th term using the closed form.
https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression
function(n,s=5^.5)round((s/2+.5)^n/s)
Pure, 66 bytes
using system;do(printf"%Zd\n")(f 1L 1L with f a b=a:f b(a+b)&end);
First answer in Pure \o/
Prints until TIO stops it or the heat death of the universe, whatever comes first.
How:
using system;do(printf"%Zd\n")(f 1L 1L with f a b=a:f b(a+b)&end); // Anonymous lambda;
using system; // Import system functions
do // Infinite loop
(printf"%Zd\n") // Print bigints + linefeed
(f 1L 1L // Declare f with 2 bigint args
// starting with 1
with f a b= // with f(a,b) being
a:f b(a+b) // a list from a until f(b,(a+b));
& // transformed into a stream
// to prevent overflowing
end);
Python 3, 43 Bytes
a,c=0,0;b=1
while 1:print(a);c=a+b;a=b;b=c
Tcl, 71 bytes (function implementation=43, Enter=1, call=27)
proc F x {expr $x>1?\[F $x-1]+\[F $x-2]:$x}
while 1 {puts [F [incr i]]}
Serves both purposes: Has a function F that allows calculate the x'th Fibonacci number. then it is called to show on stdout F applied to the whole range of positive integers.
Little Man Computer, 45 bytes, 8 instructions
Note: both answers only work up to \$ f(15) = 987 \$, as the maximum value for an integer in LMC is \$ 999 \$.
The first solution generates Fibonacci numbers 'indefinitely':
LDA 7 ADD 8 STA 7 SUB 8 STA 8 OUT BRA 0 DAT 1
and is assembled into RAM as
507 108 307 208 308 902 600 001
86 bytes, 14 instructions
The second solution returns the Fibonacci number at the index given (0-based indexing):
INP STA 0 LDA 12 ADD 14 STA 12 SUB 14 STA 14 LDA 0 SUB 13 BRP 1 LDA 14 OUT DAT 1 DAT 1
...which is assembled into RAM as:
901 300 512 114 312 214 314 500 213 801 514 902 001 001
You can test these on the online simulator here.
Burlesque, 8 bytes
Update: With current WIP one can use 1J2q?+C~.
Shortest way to produce [fib(0)..fib(n)] without trashing the stack (14B):
{0 1q?+#RC!}RS
Explanation
There's the concept of "Continuation" in Burlesque which basically means that
you run a function on a stack without destroying the stack. Fibonacci is the perfect example use-case for what these continuations are good for. If you have a program like 1 1 add then this results in a stack of 2 because add destroys the data. If add were not to destroy the data the stack would look like 1 1 2 and if we just do 1 1 add add it would look like 1 1 2 3. So all we need to do to generate a Fibonacci sequence is to call add n-times without popping the arguments. A continuation takes a snapshot of the stack, runs the function, pops the result from the stack, reverts the stack to the snapshot and pushes the result of the function to it. C! is the Burlesque built-in for "run this continuation n-times". However, doing so would trash our stack (which is no problem if you just want to print out Fibonacci numbers). Otherwise we need to use the RS built-in which runs a function in a different stack environment. RS takes a value as an argument, creates an empty stack, pushes that value to it and then runs the given function on that stack and after the function has run it will collect that stack into a list and push that list to the main stack. #R rotates the stack because the stack layout will look like N 0 1 but we need that N because it's the argument for C! so we rotate the stack. q?+ is just shorthand for {?+} (q wraps the next token into a block).
If you don't care about trashing the stack you just drop the RS:
blsq ) 10 0 1q?+#R!C
0
1
1
2
3
5
8
13
21
34
55
89
Shortest way to produce fib(n) as a reusable non stack-trashing piece of code I can think of is (17B):
0 1{Jx/?+}#RE!jvv
Older Stuff
There's dozens of ways to do that. These push the fibonacci numbers to the stack:
blsq ) 0 1{#s2.+++}10E!
blsq ) 0 1q?+10C!
However, the snippets above will also trash your stack. Alternatives for that are either:
blsq ) 0 1{Jx/?+}10E!jvv
which just computes the 10th fibonacci number. Also by still using continuations you can let the whole thing run in a seperate stack environment like uhm so:
blsq ) {10}{0 1q?+#RC!}rs
{89 55 34 21 13 8 5 3 2 1 1 0}
blsq ) 10{0 1q?+#RC!}RS
{89 55 34 21 13 8 5 3 2 1 1 0}
Really depends on your needs.
Pip, 10 9 bytes
(The language is newer than the question.)
W1o:y+YPo
Outputs infinite Fibonacci numbers on separate lines, beginning with 1. Try it online!
Explanation
The easy part is W1, which uses 1 as an always-truthy condition to create an infinite while loop.
We use two built-in variables, o and y, which are initially 1 and "", respectively. Note that an empty string in arithmetic contexts is treated as 0. At each iteration, y will hold the smaller of two consecutive Fibonacci numbers, and o will hold the larger.
The loop body is a single expression: o:y+YPo. It's important to know that Pip evaluates a binary-operator expression by first evaluating the left operand, then the right operand, then performing the operation. So, using the third iteration as an example (y is 1, o is 2):
- The left operand of
:(the assignment operator) iso; we'll computey+YPoand then assign that value too. - The left operand of
+isy, which is currently1. - The right operand of
+isYPo.YPis a unary operator that takes the value of its operand--here,o, which is2--prints it, and yanks it intoy. So whenYPois evaluated,2is printed,yis set to2, and the expression evaluates to2. +adds1and2and gives3.:assigns3too.
The end result is that 2 is printed, y becomes 2, and o becomes 3. Repeat ad infinitum.
Prolog, 36 35 29 bytes
X+Y:-writeln(X),Z is X+Y,Y+Z.
Run with 1+1.
(I don't think having to call the base case is cheating, but let me know.)
Prints the first parameter and a newline, sets Z to X+Y, then does a recursive call.
Edit 1: Can use writeln(X) instead of write(X),nl, saving one character.
Edit 2: Can use X+Y as a predicate instead of f(X,Y), saving 6 characters. Also the initial call is shorter.
Rust, 100 characters
|n|{let mut a=1u64;let mut b=1u64;let mut s=vec![a,b];for _ in 0..n {let t=b;b=a+b;a=t;s.push(b);}s}
A closure that takes an integer n as input and returns a vector of the first n items of the Fibonacci sequence.
Pascal (FPC), 70 bytes
var i,j:word;begin i:=1;repeat writeln(i);i:=i+j;j:=i-j until 1<0 end.
Prints the sequence forever, 1-indexed.
Explanation:
var i,j:word; //declare 2 integers, i and j;
//word gives range [0,65535];
//for bigger ranges, you can use Int32, Int64 or QWord
begin
i:=1; //set i to 1
//j has not been set, so it gets 0 as initial value
repeat //start a block to be repeated (first time enters unconditionally)
writeln(i); //write current value of i with a newline to separate numbers
//i needs to get the value of the next number, which is obtained by adding i and j
i:=i+j; //j is used to keep track of the last written value
j:=i-j //which is used in the next iteration;
//since i is now the sum of 2 previous values in the sequence
//and j is the earlier one, the later one can be obtained
//by substracting current j from i
until 1<0 //end a block to be repeated
//condition is always false, so the program will loop in repeat block forever
end.
Alumin, 19 bytes
zhdnqhhhhhdaodradnp
Explanation
zhdnqhhhhhdaodradnp
zh push 0, 1 [0, 1]
dn output 1 [0, 1]
q p loop (forever)
hhhhh push 5 [0, 1, 5]
da double (10) [0, 1, 10]
o output as char (newline) [0, 1]
d duplicate TOS [0, 1, 1]
r reverse stack [1, 1, 0]
a add top two [1, 1]
dn output top w/out popping [1, 1]
Tidy, 15 bytes
recur2(1,1,(+))
Try it online! Returns an infintie range of Fibonacci numbers.
Explanation
recur2 defines a recursive function which takes the previous 2 items and applies a function to them, in the case, addition. This is equivalent to saying "the first two entries are both 1 and every entry after that is the sum of the previous two".
05AB1E, 2 bytes
Åf
1-indexed. Built-in.
05AB1E, 2 bytes
λ+
0-index. Non-built-in. As far as I know, this is the first answer using the major 05AB1E rewrite, and uses its newest addition, λ...}, recursive list generation.
How it works
λ+ – Full program.
λ – Starting from 1, recursively apply a function and collect the results
in an infinite list.
+ – Addition.
AsciiDots, 22 21 20 17 16 15 bytes
/.{+}-\
\#$*#1)
Prints the Fibonacci sequence. Outgolfs the sample by 12 13 14 17 18 19 bytes. This is now just 1 byte longer than exactly as long as a simple counter! Try it online!
AsciiDots, 31 30 bytes
/#$\
.>*[+]
/{+}*
^-#$)
\1#-.
Here's a faster version. It prints out the Fibonacci sequence at a rate of 1 number per 5 ticks, compared to the maximally golfed version's 1 per 8 10 8 12 14 ticks. It's twice as fast as the sample and is still shorter by 3 4 bytes! Try it online!
Ahead, 15 bytes
1loN+{<
>\:O\:^
Uses signed 32-bit ints so eventually reaches overflow and wraps negative. Starts at 0, which is technically correct?
Binary-Encoded Golfical, 27+1 (-x flag)=28 bytes
Noncompeting, language postdates the question.
Hexdump:
00 90 02 00 01 14 0C 01 14 00 00 14 1B 1E 08 01
14 2C 17 0A 01 3A 0C 01 2D 1C 1D
This encoding can be converted back to the original image using the github repo's included Encoder utility (java Encoder d "<encoded file>" "<target file>") or run directly by adding the -x flag
Original image:

Magnified 50x:

Rough translation:
*p=1;
*(p+1)=*p;
*p=0;
while true:
p++;
push *p;
p--;
*(p+1)=*p;
*p=pop;
*p+=*(p+1);
print *p;
end while;
x86 assembly (32-bit), 14 bytes
Bytecode:
58 59 50 41 31 c0 99 40 01 c2 92 e2 fb c3
That 3-byte add/xchg is quite concise :-)
1-indexed.
0: 58 pop %eax
1: 59 pop %ecx
2: 50 push %eax
3: 41 inc %ecx
4: 31 c0 xor %eax,%eax
6: 99 cltd
7: 40 inc %eax
8: 01 c2 add %eax,%edx
a: 92 xchg %eax,%edx
b: e2 fb loop 8
d: c3 ret
Julia 0.6, 19 bytes
!a=round(φ^a/√5)
This is 16 chars and 19 bytes, a goof way to abuse Julia beats the existing Julia answers which were 20 bytes. by 1 bytes and 3 chars
µ6, 16 bytes
[>#[,.[+.]][[,>[#/0[+/1]<>]]/1]]
Explanation
[> -- right element of the tuple generated by
# -- | primitive recursive function
-- | base case:
[, -- | | pair of
. -- | | | constant zero
[+.] -- | | | successor of constant zero
] -- | | : (0,1)
-- | recursive case:
[ -- | | compose the two
[, -- | | | pair of
> -- | | | | the right element
[#/0[+/1]<>] -- | | | | add left & right element
] -- | | | (snd, fst + snd)
/1 -- | | | second argument (we only need the tuple)
] -- | : (f (n-1), f (n-2) + f (n-1))
] -- : f n
Python 2, 33 31 bytes
i=j=1
while 1:print j;i,j=j+i,i
Uses a loop to infinitely print the sequence. Will eventually error out due to integer overflow. It has been pointed out to me that Python uses arbitrary precision integers. Learn something new every day!
Javascript, 57 bytes
_=1;i=0;for(z=10;z--;)alert((a=>!(o=_+i)+(i=_)+!(_=o))())
Retina 0.8.2, 23 bytes
.+
$*
+`11(1*)
1$1 $1
1
Try it online! Explanation:
.+
$*
Convert to unary.
+`11(1*)
1$1 $1
Repeatedly replace all n greater than 1 with copies of n-1 and n-2, thus calculating f(n) = f(n-1) + f(n-2) for n greater than 1.
1
Count the remaining 1s, as f(0) = 0 and f(1) = 1.
Add++, 74 bytes
D,f,@@@@*,V$2D+G1+dAppp=0$Qp{f}p
D,r,@,¿1=,1,bM¿
D,g,@,¿1_,1_001${f},1¿{r}
Old version, 75 bytes
D,f,@@@@*,V$2D+G1+dAppp=0$Qp{f}p
D,r,@:,1b]$oVcGbM
x:?
-1
I,$f>x>0>1>0
$r>x
It's long, but I rather this than have a builtin. Takes a single input n, and outputs the nthe Fibonacci number.
How it works
Executable demonstration with an example input of 8:
D,fib,@@@@*, ; Create a tetradic function 'fib'
; This returns the nth and (n-1)th fib number
; Example arguments: [8 0 1 0]
V ; Save the top value; [8 0 1] ; 0
$ ; Swap; [8 1 0] ; 0
2D ; Take the 2nd value; [8 1 0 1] ; 0
+ ; Sum; [8 1 1] ; 0
G ; Retrieve; [8 1 1 0]
1+ ; Increment; [8 1 1 1]
d ; Duplicate; [8 1 1 1 1]
A ; Push the arguments; [8 1 1 1 1 8 0 1 0]
ppp ; Pop 3 values; [8 1 1 1 1 8]
= ; Cond: Equal? [8 1 1 1 0]
0$Qp ; If: Return 0
{fib}p ; Else: Call 'fib' again
; Eventually, this returns:
; [7 13 21 7 0]
D,ret,@:, ; Create a monadic function 'ret' that outputs the final result
; Example argument: [[7 13 21 7 0]]
1b] ; Push [1]; [[7 13 21 7 0] [1]]
$ ; Swap; [[1] [7 13 21 7 0]]
o ; Logical OR; [[1] [7 13 21 7 0]]
VcG ; Clear all but one; [[7 13 21 7 0]]
bM ; Take the maximum; [21]
x:? ; Take input; x = 8
-1 ; Decrement; x = 7
I, ; If x != 0:
$fib>x ; Call 'fib' x = [7 13 21 7 0]
>0>1>0 ;
$ret>x ; Call 'ret' x = 21
Lean, 42 35 bytes
7 bytes thanks to Mario Carneiro.
def f:_->nat|(n+2):=f(n+1)+f n|x:=x
Lean is a completely different kind of a programming language: it is a proof-assistant. That means, mathematical theorems can be formalized and proved in Lean, and mathematical objects can be constructed in Lean.
In this case, the auto-generated correctness theorems are (cf tio link):
f.equations._eqn_1 : f 0 = 0
f.equations._eqn_2 : f 1 = 1
f.equations._eqn_3 : ∀ (n : ℕ), f (n + 2) = f (nat.succ n) + f n
Elixir, 49 bytes
Defines a function to get the nth fibonacci number. 1-indexed (starts at 0).
Simple recursive formula. Slow.
def f(n)when n<2,do: n
def f(n),do: f(n-1)+f(n-2)
Elixir, 50 bytes
Returns an infinite stream of fibonacci numbers. 1-indexed (starts at 0).
Fast, carries over an accumulator with the sum of the previous two numbers.
fn->Stream.unfold{0,1},fn{a,b}->{a,{b,a+b}}end end
R16K1S60 Assembly, 36 bytes
mov bx, ip
mov ax, ip
mov sp, data
jmp inner
prg:
mov cx, [sp+ax]
mov [sp+bx], cx
inner:
mov ex, [sp]
mov dx, [sp+bx]
mov [sp], dx
add ex, dx
mov [sp+ax], ex
send ax, ex
jmp prg
data:
dw 0x0000
dw 0x0001
Pretty simple. Abuses 7 registers, including the instruction pointer (for some predefines)
To note why I used the IP instead of a constant, it's because the R16K1S60 has to use an extra word (two bytes) to encode a constant into an instruction.
Alongside that, I used ax and bx instead of ex and dx for the offset because ex and dx cannot be referenced in only 3 bits (the size of the offset section of instructions that support it)
Outputs the number as a word on port 2
SmileBASIC, 28 bytes
F.,1DEF F X,Y?Y
F Y,X+Y
END
Ungolfed:
F 0,1
DEF F X,Y
PRINT Y
F Y,X+Y
END
Dodos, 26 bytes
dot F
F
F dip
F dip dip
How it works
The function F does all the heavy lifting; it is defined recursively as follows.
F(n) = ( F(|n - 1|), F(||n - 1| - 1|) )
Whenever n > 1, we have |n - 1| = n - 1 < n and ||n - 1| - 1| = |n - 1 - 1| = n - 2 < n, so the function returns ( F(n - 1), F(n - 2) ).
If n = 0, then |n - 1| = 1 > 0; if n = 1, then ||n - 1| - 1| = |0 - 1| = 1 = 1. In both cases, the attempted recursive calls F(1) raise a Surrender exception, so F(0) returns 0 and F(1) returns 1.
For example, F(3) = ( F(1), F(2) ) = ( 1, F(0), F(1) ) = ( 1, 0, 1 ).
Finally, the main function is defined as
main(n) = sum(F(n))
so it adds up all coordinates of the vector returned by F.
For example, main(3) = sum(F(3)) = sum(1, 0, 1) = 2.
Stax, 2 bytes
|5
Added for completeness. An internal that returns 0-indexed Fibonacci number.
Infinite sequence generator without using the internal:
ò¶AÄ∟
The ASCII equivalent is
01WQb+
Whitespace, 50 47
Replace S,T,L with Space,Tab,Linefeed:
SSSLSSSTLSLSTLSTLSSSLSLSSTSSTSLTSSSSLSTLSTLSLSL
Explanation:
push 0 SS SL
push 1 SS STL
dup SLS
outn TLST
lbl 0 LSS SL
dup SLS
cpy 2 STS STSL
add TSSS
dup SLS
outn TLST
jmp 0 LSL SL
Outputs all the Fibonacci numbers concatenated (the question didn't mention separating them :)
1123581321345589144233377610987159725844181676510946...
(Thanks to @KevinCruijssen for -3 bytes.)
Reflections, 93 bytes
\
/*\/# (0:0\
* 0\_*;(0\/ :(0\
\ v/#@/_ /
\ (1/ 1)0)*
: \\/
\(1/
Explanation:
Initialisation
Executing \*/(1\*/*\0\.
*at (5|2) pushes 5×2=10 (\n)(1moves the newline to stack 1*at (0|2) pushes 0×2=0 (F(-1))*at (1|1) pushes 1×1=1 (F(0))0moves these two values to stack 0
Loop
Executing v1):\(1/\\0)#/:(0\/_//\*@\0:(0#/\_*;(0\/.
1)pulls the newline from stack 1:duplicates it(1moves the duplicate to stack 10)pulls the last result from stack 0#redefines (0|0):duplicates the last result(0moves the duplicate back to stack 0_at (3|0) converts the last result to a list of digits*at (1|1) pushes 1×1=1@prints the last result and a newline0pulls both values from stack 0:duplicates the top one (newer one)(0pushes the duplicate back to stack 0#redefines (0|0)_at (0|1) adds the two values together*at (1|1) pushes 1×1=1;pops that again(0pushes the new result to stack 0
Forked, 17 15 bytes
01v
>sP+%A!"U
This uses the same method as my Implicit answer.
The first line sets up the stack: pushes 0, pushes 1, and then directs the control flow South.
The > on the second line turns the IP East where it hits the main code:
sP+%A!"U
s- swap top two stack valuesP- pop top of stack, store in register+- pop top two stack values, add together, push result%- print top of stack as integerA!- print 0xA as codepoint character (ASCII newline)"- swap top two stack valuesU- push register to stack
Since the IP wraps, this line is executed infinitely.
Momema, 28 bytes
1 1z0-8*01+*1*00+*1-*0-9 9z1
Try it online! Outputs infinitely with a tab between numbers.
If no separator between numbers is required, you can save four bytes:
1 1z0-8*01+*1*00+*1-*0z1
Explanation
# a = 0
1 1 # [1] = 1 # b = 1
z 0 # label z0: jump past label z0 (no-op) # while true {
-8 *0 # output num [0] # print a
1 +*1*0 # [1] = [1] + [0] # b = a + b
0 +*1-*0 # [0] = [1] - [0] # a = b - a
-9 9 # output chr 9 # print '\t'
z1 # label z1: jump past label z0 # }
Japt, 3 bytes
Just to add to the collection.
0-indexed, using 0 as the first number in the sequence.
MgU
FALSE, 13 bytes
1 1[1][$2ø+]#
Numbers are pushed to the stack.
Common Lisp, 38 bytes
Generates the Fibonacci sequence without end.
(do((a 1 b)(b 1(+ a b)))(())(print a))
The other Common Lisp solution is a function to generate the n-th number. This solution works since in the do loop the assignments to the iteration variables are performed in parallel: so the initialization is equivalent to:
a, b = 1, 1
while at each repetition the assignment is equivalent to:
a, b = b, a+b
QBasic, 32 bytes
b=1
DO
?b
b=b+a
a=b-a
SLEEP
LOOP
Generates and prints Fibonacci numbers forever. SLEEP waits for a user keypress between numbers; otherwise, the output would scroll off the screen very rapidly.
tinylisp, 40 bytes
The language is much newer than question, of course.
(d f(q((x y)(i(disp x)1(f y(a x y
(f 0 1
This is a full program that outputs Fibonacci numbers until you stop it. Try it online!
The first line defines a function f that takes numbers x and y, outputs x, and calls f recursively on y and the addition of x and y. The main trick is the use of if to simulate a "do A, then B" structure: the disp call is used as the condition; its return is always falsey; so we put the recursion in the false branch.
The second line calls f with 0 and 1.
Pyt, 1 byte
Get the nth Fibonacci number:
Ḟ
Explanation:
Implicit input
Ḟ Return (input)-th Fibonacci number
Pyt, 7 bytes
Get an infinite list of Fibonacci numbers:
0`ĐḞƤ⁺ł
Explanation:
0 Push 0 [this is the counter]
` ł While the counter is not zero (checked at 'ł')
Đ Duplicate the counter
ḞƤ Print the (counter)-th Fibonacci number
⁺ Increment the counter
><>, 12 Bytes
10:r+:nao20.
Output:
1
1
2
3
5
...
Could save 2 bytes by removing the new line, but then there would be no separation in the output at all.
Explanation:
Pretty basic. Start by pushing 1, 0 to the stack. Duplicate the top item, reverse the stack, and sum the top two items. If we had f_n, f_n-1 on the stack before, we now have f_n+1, f_n. Duplicate the top item, and print it. 'ao' prints a new line. '20.' moves the pointer to (2,0) in the codebox, which is right after the '10'. Start again.
Implicit, 12 11 bytes
]3.(,[+%:]ß
10 bytes (knock off the ß) if we don't need delimiters. It's not specified in the challenge... TIO
This is my own (rather simple) method of computing the sequence. Explanation:
#::.(,[+%:]ß
#::. push 0, 0, 1 (push stack length, duplicate twice, increment last one)
(....... forever (implicit ¶ at end of program)
, swap top two stack values
[ pop stack into memory
+ add top two stack values
% print
: duplicate top of stack
] push memory to stack
ß print a space
In a normal language, say, C, it would look like this:
int x, y, z;
x = 0; y = 0; z = 1;
do {
swap(&y, &z);
x += y;
y = x;
printf("%d ",x);
} while (1);
Equivalence:
int x = 0, y = 0, z = 1; // #::.
do { // (
swap(&y,&z); // ,
// [ (z is ignored below)
x += y; // +
y = x; // :
printf("%d ",x); // %ß
// ] (z is ignored above)
} while (1); // ¶
Here's how the stack looks after each operation that modifies it:
# 0
: 0 0
: 0 0 0
. 0 0 1
, 0 1 0
[ 0 1
+ 1
% 1
: 1 1
] 1 1 0
, 1 0 1
[ 1 0
+ 1
% 1
: 1 1
] 1 1 1
, 1 1 1
[ 1 1
+ 2
% 2
: 2 2
] 2 2 1
, 2 1 2
[ 2 1
+ 3
% 3
: 3 3
] 3 3 2
, 3 2 3
[ 3 2
+ 5
% 5
: 5 5
] 5 5 3
, 5 3 5
[ 5 3
+ 8
% 8
: 8 8
] 8 8 5
, 8 5 8
[ 8 5
+ 13
% 13
: 13 13
] 13 13 8
, 13 8 13
[ 13 8
+ 21
% 21
: 21 21
] 21 21 13
, 21 13 21
[ 21 13
+ 34
% 34
: 34 34
] 34 34 21
Golf notes:
]3.is shorter than#::.which is shorter than:0::1which is shorter than:0:0:1.ßis shorter than@32.(...is shorter than:1(;...:1).
(ß, ¶, and implicit ¶ added during the writing of this program.)
C, 64 bytes
a,x,y,z=1;main(){for(;;){a=y;y=z;z=a;x+=y;y=x;printf("%d ",x);}}
Try it online! Uses the same method as my Implicit answer.
Pug, 30 bytes
Without input (infinite)
-a=b=1
while 1
=a
-b=a+(a=b)
Will produce an output:
1123581321345589144233377610...
With an output delimiter: 34 bytes
-a=b=1
while 1
=a+" "
-b=a+(a=b)
Will produce an output:
1 1 2 3 5 8 13 21 34 55 89...
With HTML as an output delimiter: 31 bytes
-a=b=1
while 1
p=a
-b=a+(a=b)
Although I doubt this is compliant to the challenge's rules, this will produce:
<p>1</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>5</p>
<p>8</p>
<p>13</p>
<p>21</p>
<p>34</p>
<p>55</p>
...
With input (as a funcion; finite)
Without an output delimiter, 47 bytes
mixin f(n)
-a=b=1
while n--
=a
-b=a+(a=b)
For an input n=10, for example, it produces:
11235813213455
Just as it is with the infinite series versions:
- +4 bytes (
+" ") = 51 bytes for a space delimiter - +1 byte (
p) = 48 bytes for an HTML<p>tag delimiter
VBA, 28 Bytes
Anonymous VBE immediate window function that takes no input and infinitely outputs the n-th term of the Fibonacci Sequence while iterating n
i=1:Do:k=i+j:i=j:j=k:?j:Loop
J-uby, 8 6 bytes
:++2.*
In J-uby, + on a proc (or a symbol in this case, as symbols can be used as procs in J-uby), defines a recurrence relation. It takes a starter array, and then produces a function that takes n, and then applies itself to the starter array n times, pushing the result to the end and removing the first element. Naturally :+ + [0,1] is a recurrence relation that starts with elements 0, 1 and adds them together n times.
2.* is shorthand for [0,1]
Cy, 11 + 1 (-p flag) = 12 bytes (non-competing)
This is going for the infinite stream
0 1 $&+ &do
(the -p flag implicitly prints every non-block value pushed to the stack)
Literally,
- push 0
- print it
- push 1
- print it
- forever
- push the sum of the last two items
- print it
Without the -p flag semi-cheat:
Cy, 24 bytes
0 &:< 1 &:< {&+ &:<} &do
Chip-8, 36 bytes
6301 'LD v3,1
6D05 'LD vD,5
6E0A 'LD vE,A
8344 'ADD v3,v4
A200 'LD I,200
F333 'LDD [I],v3
8343 'XOR v3,v4
8433 'XOR v4,v3
8343 'XOR v3,v4
F265 'LD v2,[I]
F029 'LDF I,v0
00E0 'CLS
DFF5 'DRW vF,vF,5
F129 'LDF I,v1
DDF5 'DRW vD,vF,5
F229 'LDF I,v2
DEF5 'DRW vE,vF,5
1206 'JMP 206
Displays Fibonacci numbers (up to 233) in decimal. (It might be shorter to use hexadecimal, but I think that's cheating)
This one writes the numbers into memory:
6001
A300
8014
F055
8013
8103
8013
1204
... but it's actually longer than valid numbers it writes:
01 01
02 03
05 08
0D 15
22 37
59 90
E9 79 (overflow)
Recursiva, 16 bytes
<a3:1!+#~a$#~~a$
Explanation:
<a3:1!+#~a$#~~a$
<a3:1 - If a<3 then 1
! - Else
+ - Sum
#~a$ - Call Self but with parameter a-1, will be replaced by result
#~~a$ - Call self but with parameter a-2, will be replaced by result
Axiom, 35 bytes
a(0)==0;a(1)==1;a(n)==a(n-1)+a(n-2)
above it is one succession defined by Recurrence... Results
(7) -> [a(i) for i in 0..20]
(7) [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765]
Pylons, 13 bytes
Takes the number of iterations as a command line argument to the interpreter.
11fA..+@{A,i}
How it works:
11 # Pushes 1, 1 to the stack.
fA#.##.#+@ # Creates a function "A" that takes the top two elements of the stack and adds them.
{A,i} # Calls A sys.argv[1] times.
Piet, 17 codels
Not sure how to count this one. There are 17 pixels within the code that count as instructions/control flow modifiers (18 if you count the required NOP to get the color back to the correct cycle for the loop).
Shown here at 20 pixels per codel:
Explanation in pseudocode:
push 1
push 1
push 1
push 1
out (number)
out (number)
START OF INFINITE LOOP
duplicate
push 3
push 1
roll ; the last three instructions amount to "rotate the top to the third spot once"
add
duplicate
out (number)
END OF INFINITE LOOP
This outputs the Fibonacci sequence (starting with 1,1) without delimiters.
Jelly, 3 bytes
+¡1
How it works
+¡1 Niladic link. No implicit input.
Since the link doesn't start with a nilad, the argument 0 is used.
1 Yield 1.
+ Add the left and right argument.
¡ For reasons‡, 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.
‡ ¡ peeks at the two links to the left. Since there is only one, it has to be the body of the loop. Therefore, a number is read from input. Since there are no command-line arguments, that number is read from STDIN.
Tampio, 107 bytes
uni on 1 lisättynä 1:een lisättynä yhteenlaskuun sovellettuna unen jäseniin ja unen hännän jäseniin
Explanation:
uni on 1 lisättynä 1:een lisättynä
uni = 1 : 1 :
yhteenlaskuun sovellettuna unen jäseniin ja unen hännän jäseniin
(+) `zip` (uni , tail uni )
Klein, 23 22 21 + 3 = 24 bytes (non-competing)
Run with the 000 topology
(1)\((@
):?\1-+(:(+)$
Explanation
When the program starts it executes (1) which will put a 1 under the input. It then deflects into the main loop.
The main loop is on the second line. It starts with the \ character. Unwrapped it looks like:
\1-+(:(+)$):?
This will redirect our pointer if the counter is zero or perform one iteration of the fibonacci sequence otherwise.
Once the counter reaches zero we are deflected to the code ((@, this will hide the top two values (the counter and one of the fibonacci numbers) and terminate the program.
Element, 12 (option two) or 11 (option one)
I've decided to go back in time and answer some classic golfing questions with Element to give it some more street cred.
The following code prints out the Fibonacci sequence continuously (it overflows rather quickly). Each number is printed separately, although there is no whitespace separation.
1!{4:`~2@+}
1 push 1 onto the stack
! flip the empty control stack to 1 to enable looping
{ } infinite while loop
{4: } have 4 copies (3 additional) of the newest number on the stack
{ ` } output one copy
{ ~ } A fancy way to get zero from a copyusing the variable retrieval function
{ 2~ } Move one copy from position 0 to position 2 (behind the old number)
{ +} add the number to the old number
The following code inputs a number and outputs the Nth number in the sequence (0-indexed).
1_'[3:~2@+]`
1 push a 1
_' take input then move it to the control stack
[ ] FOR loop
[3: ] make two additional copies of the top number (3 is the total count)
[ ~ ] turn one copy into a zero
[ 2@ ] move from position 0 to position 2, behind the old number
[ +] add the old and newer number
` output the result
For completion's sake, here is a link to the interpreter.
C, 224 229 227 chars
...prints the n'th fibonacci or 2^n
Golfed up:
#import <Foundation/Foundation.h>
typedef unsigned long long f;f main(int c,char*v[]){f n=strtoull(v[1],(char**)v[2],10)-1;f x=(c>2&&++n==0)?0:1;f y=0;while(n--!=0&&x+y>=x&&x>0){f z=x;c>2?x+=y=z:(x+=y,y=z);}printf("%llu\n",x);}
Readable:
#import <Foundation/Foundation.h>
typedef unsigned long long f;
f main(int c,char*v[]){
f n=strtoull(v[1],(char**)v[2],10)-1;
f x=(c>2&&++n==0)?0:1;
f y=0;
while(n--!=0&&x+y>=x&&x>0){
f z=x;
c>2?x+=y=z:(x+=y,y=z);
}
printf("%llu\n",x);
}
If the number exceeds the length of an unsigned long long it will print the highest it can get.
Return type is f (unsigned long long) for short code, it does generate 2 compiler warnings and a note but it still compiles!
It also has the option to calculate 2^n because it initially printed that.
Usage:
./fibbin 42- prints42'th fibonacci number (267914296)./fibbin 42 anyInputHere- prints 2^n(4398046511104).
Don't enter values of 0, higher than 93 (fibonacci) or higher than 63 (2^n).
Examples:
./fibbin 1=1./fibbin 2=1./fibbin 3=2./fibbin 4=3./fibbin 42=267914296./fibbin 92=7540113804746346429./fibbin 93=12200160415121876738- this is the highest i can go./fibbin 94= should be 19740274219868223167, but it doesn't fit into an unsigned long long so i will print #93./fibbin 1 bin-2./fibbin 2 bin-4./fibbin 3 bin-8./fibbin 4 bin-16./fibbin 42 bin-4398046511104./fibbin 62 bin-4611686018427387904./fibbin 63 bin-9223372036854775808- this is the highest i can go./fibbin 64 bin- should be 18446744073709551616, but it doesn't fit into an unsigned long long so i will print 0
These tests match the output of wolfram-alpha, due to the heavy calculations wolfram may time out but it generally doesn't.
PHP, 39 bytes
<?php for($b=1;;)echo$a=-$a+$b+=$a,' ';
Explanation
<?php
An infinite loop is started. The zero-th term in the series, initially $a, is 0, so needn't be assigned. $b
is initially the second term and so is set to 1.
for ($b = 1;;)
The part which does all the work is echo $a = -$a + $b += $a, ' ';. Here it is
expanded.
{
Calculate the new value for $b: the next term is the sum of the previous two.
$b = $b + $a;
$a needs to be moved on one term as well. It is calculated by subtracting itself
from the new value of $b.
$a = $b - $a;
For byte-saving convenience, it is $a that is echoed each time—followed by a space!
echo $a, ' ';
}
Proton, 24 bytes
f=a=>a<2?1:f(a-1)+f(a-2)
(Not working on TIO yet; waiting for pull)
The @ is not necessary but it enables caching for the lambda which makes it considerably faster (as in, it actually finishes in a reasonable amount of time). That being said, when I tried computing it up to 10000 (which I needed to increase sys.setrecursionlimit to do), it gave me a Segmentation Fault because the program ran out of memory (Proton is very inefficient) :P
Forth, 39 36 bytes
0 1 : f BEGIN 2DUP + ROT . AGAIN ; f
Explanation
First 0 and 1 are pushed to the stack.
Then starts an endless loop where 2DUP duplicates the top two stack items which are then summed with +. At this point stack is 0 1 1. Then the bottom item of the stack is moved on top with ROT. . prints and removes the item on the top of the stack. Creates an endless sequence of Fibonacci numbers.
Had to check out what's Forth about. And is there a better way to learn than trying to golf Fibonacci series. I see that there's already an answer with Forth but desided to post anyway. At least this is a different approach.
Python 2, 49 40 chars
a,b=0,1
exec"a,b=b,b+a;"*input()
print b
Function form, 44 chars
def f(n):a,b=0,1;exec"a,b=b,b+a;"*n;return b
My take on this challenge. Didn't find this kind of an answer yet. I hope it's a valid one.
Print's n:th Fibonacci number. Functions by multiplying the string inside exec n times and then executing it as Python.
Edit: input() instead of int(raw_input())
Python 2, 34 bytes
Python, using recursion... here comes a StackOverflow!
def f(i,j):print i;f(j,i+j)
f(1,1)
Gaia, 6 bytes
0₁@+₌ₓ
I might make a built-in for this in the future, but built-ins are boring anyway.
Explanation
0₁ Push 0 and 1
@ Push an input
+₌ₓ Add the top two stack elements, without popping them, (input) times
Implicitly print the top stack element.
ReRegex, 50 bytes.
(0+),(0+):0/$1,$2,$1$2:/.*?(0+),0+:$/$1/0,0:#input
0 indexed. Takes input and gives output via Unary.
About the Program
ReRegex was designed to be much like an advanced version of ///. It offers the same very basic concept of repeatedly doing string match and replace operations. However, that's where the similarities end. ReRegex instead uses a list of match and replace operations, separated by /s, to perform in a loop, and the original string to effect. The Regexes will continue being performed on the original string until a constant state is achieved, at which point the program will dump the string to STDOUT.
This program in particular is just 2 regular expressions and then the input with some default values.
(0+),(0+):0 -> $1,$2,$1$2:
.*?(0+),0+:$ -> $1
And the input is formatted with;
0,0:#input
ReRegex defaultly replaces #input with whatever is passed to the program on STDIN.
For an example, let's say 00000 is passed to STDIN. First, the "Memory" looks like this:
0,0:00000
In the first loop, the regex (0+),(0+):0 is matched, the replace then creates the next itteration of the fibonnachi sequence.
0,0,00:0000
And in doing so, it also pops one of the 0's off, which is why :0 is at the tail end of the match, but not the replace. This then happens 4 more times in a row.
0,0,00,000,00000,00000000,0000000000000:
Now that first regex doesn't match, as there's no more :0 at the end, so we're almost at a stable end point. Now that there's nothing after :, .*?(0+),0+:$ matches, and all it does is clear all data but the second last group of 0s.
00000000
Now, nothing else matches, so it's outputted.
Python 2, 30 bytes
f=lambda n:n<3or f(n-2)+f(n-1)
One catch: this outputs True instead of 1. This is allowed by this meta consensus.
cQuents, 6 bytes
=1:z+y
This works both with and without input - it prints the sequence without input, and the nth item (1-indexed) with input n.
For 0, 1, 1, ... version, 8 bytes:
=0,1:z+y
Explanation
=1 Set first item in sequence to 1
: Mode: Sequence 1 (prints sequence with no input, or nth item with input n
z+y Each term equals the previous two terms added together (defaults to 0)
I really, really like the way this language is going :)
Joy, 45 bytes
DEFINE f ==[2<][][[1 - f][2 - f]cleave+]ifte.
Try it online! Zero-indexed. Example usage: 6 f yields 8.
[2<] ifte . if the top stack element is less than two
[] . then do nothing
[ cleave ] . else duplicate the element and apply two functions
+ . and sum the results
[1 - f][2 - f] . where the functions compute the two previous Fibonacci numbers
Alternative (same byte count):
DEFINE f ==[2<][][dup 1 - f swap 2 - f+]ifte.
Java, 55
I can't compete with the conciseness of most languages here, but I can offer a substantially different and possibly much faster (constant time) way to calculate the n-th number:
Math.floor(Math.pow((Math.sqrt(5)+1)/2,n)/Math.sqrt(5))
n is the input (int or long), starting with n=1. It uses Binet's formula and rounds instead of the subtraction.
OIL, 46 bytes
This program writes an infinite unstoppable stream of fibonacci numbers. It is mostly copied from the standard library but fit to the requirements and golfed.
14
add
17
17
14
swap
17
17
4
17
11
6
0
0
1
Taxi, 864 bytes
1 is waiting at Starchild Numerology.1 is waiting at Starchild Numerology.Go to Starchild Numerology:W 1 L 2 R 1 L 1 L 2 L.Pickup a passenger going to Sunny Skies Park.Pickup a passenger going to Cyclone.Go to Sunny Skies Park:W 1 R.[a]Go to Cyclone:N 1 L.Pickup a passenger going to The Babelfishery.Pickup a passenger going to Addition Alley.Go to Fueler Up:N 2 R, 2 R.Go to The Babelfishery:S.Pickup a passenger going to Post Office.Go to Post Office:N 1 L 1 R.Go to Sunny Skies Park:S 1 R 1 L 1 R.Pickup a passenger going to Cyclone.Go to Cyclone:N 1 L.Pickup a passenger going to Addition Alley.Pickup a passenger going to Cyclone.Go to Addition Alley:N 2 R 1 R.Pickup a passenger going to Sunny Skies Park."," is waiting at Writer's Depot.Go to Writer's Depot:N 1 L 1 L.Pickup a passenger going to Post Office.Go to Sunny Skies Park:N 2 R.Switch to plan "a".
Ungolfed:
1 is waiting at Starchild Numerology.
1 is waiting at Starchild Numerology.
Go to Starchild Numerology: west 1st left 2nd right 1st left 1st left 2nd left.
Pickup a passenger going to Sunny Skies Park.
Pickup a passenger going to Cyclone.
Go to Sunny Skies Park: west 1st right.
[a]
Go to Cyclone: north 1st left.
Pickup a passenger going to The Babelfishery.
Pickup a passenger going to Addition Alley.
Go to Fueler Up: north 2nd R, 2nd right.
Go to The Babelfishery: south.
Pickup a passenger going to Post Office.
Go to Post Office: north 1st left 1st right.
Go to Sunny Skies Park: south 1st right 1st left 1st right.
Pickup a passenger going to Cyclone.
Go to Cyclone: north 1st left.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to Cyclone.
Go to Addition Alley: north 2nd right 1st right.
Pickup a passenger going to Sunny Skies Park.
"," is waiting at Writer's Depot.
Go to Writer's Depot: north 1st left 1st left.
Pickup a passenger going to Post Office.
Go to Sunny Skies Park: north 2nd right.
Switch to plan "a".
Axiom, 113 bytes
f(n:NNI):NNI==(n=0=>0;n:=n-1;x:=sqrt(5);floor(numeric(((x+1)/(2*x))*((1+x)/2)^n+((x-1)/(2*x))*((1-x)/2)^n)))::INT
code for test and results
(80) -> [f(i) for i in 0..20]
(80)
[0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765]
Type: List NonNegativeInteger
(81) -> f 100
(81) 354224848179261915076
Type: PositiveInteger
(82) -> f 200
(82) 280571172992510140037336354957747795525632
Type: PositiveInteger
(83) -> f 400
(83)
1760236806450139664680709294813170892283658770059881093310828506440687624218_
31925760
Type: PositiveInteger
(84) -> f 800
(84)
6928308186422471713609360660466569632290421684876894264783997577258487494487_
420363654234099779749410573113727333378633545181944038619446626409501657425_
3135847342735360
Type: PositiveInteger
(85) -> f 1500
(85)
1355112566856310195162377575526951323656561770431639555079987987810736653460_
922122221302671882558120755439823360357867711740787668744312284056217232330_
713983569575833249689158528416736647370129969548463847884661978641646883591_
466734576231634867107272686298047871451723693301109753896341229444935835304_
2229054930944
Type: PositiveInteger
(86) -> f 2000
(86)
4224696333392304878698067179976673472756391964001565086095500593531167791551_
743662247281607190958887487440686606420026093467732621145548367502217030083_
858092272596709322168369132666938424515347258074945014044152199085287931830_
556530989999311940427567701708311778838430925973655760228465275886647451746_
556255968313014088560151159533857580044154666168801306507492995800168547537_
206536250047308876795741658264221262020608
JavaScript (ES6)
A couple of different ES6 implementations. The first two return the nth Fibonacci number and the third returns an array of the first n Fibonacci numbers. Non-competing, obviously.
30 bytes
f=
(n,x=1,y=0)=>!n?y:f(n-1,x+y,x)
console.log(f(10))
46 bytes
f=
n=>(x=1,y=0,eval("while(n--)[x,y]=[x+y,x]"),y)
console.log(f(10))
46 bytes
f=
n=>(a=[],(f=x=>a[x]=x<2?x:f(--x)+f(--x))(n),a)
console.log(f(10))
Alice, 11 bytes
This was a collaborative golfing effort with Sp3000.
1 \ O
,+{.3
This prints the Fibonacci sequence indefinitely, starting from 1,1, one integer on a line. Unfortunately, it's horrible in terms of memory, because it leaks one stringified copy of each number in the sequence. The things you do for bytes...
Explanation
1 Push 1 to initialise the sequence. There's already an implicit zero underneath.
\ Reflect to NE. Switch to Ordinal.
Immediately reflect off top boundary, move SE.
The remainder of the program runs in an infinite loop. At this point of the loop
there's the current number F_n of the sequence on top of the stack, and the
previous number F_n-1 is below.
Stack:
[... F_n-1 F_n]
. Implicitly convert F_n to a string and duplicate it. [... F_n-1 "F_n" "F_n"]
Reflect off bottom boundary, move NE.
O Output F_n with a trailing linefeed. [... F_n-1 "F_n"]
Reflect off top right corner, move back SW.
. Make another copy of F_n. (We don't need this one.) [... F_n-1 "F_n" "F_n"]
Reflect off bottom boundary, move NW.
\ Reflect to S. Switch to Cardinal.
{ Turn 90 degrees left, i.e. east.
. Implicitly convert F_n to an integer and duplicate it. [... F_n-1 "F_n" F_n F_n]
3 Push 3. [... F_n-1 "F_n" F_n F_n 3]
, Pull up the third stack element, which is F_n-1. [... "F_n" F_n F_n F_n-1]
+ Add F_n and F_n-1. [... "F_n" F_n F_n+1]
{ Turn 90 degrees left, i.e. north.
\ Reflect to SE. Switch to Ordinal.
After this point, the loop repeats.
bc, 21
for(b=1;b=a+(a=b);)a
The trailing newline is significant.
Outputs the entire sequence. bc has arbitrary precision arithmetic, so this continues forever.
Mathematica, 32 26 bytes
-6 bytes thanks to @MartinEnder!
±1=±2=1;±n_:=±(n-1)+±(n-2)
Recursive function, returns nth value in sequence.
C, 33 bytes
Recursively calculates the nth fibbonacci number.
f(n){return n>1?f(n-1)+f(n-2):n;}
Forth, 27 bytes
Prints them forever (until it exceeds the maximum integer).
: f over . 2dup + recurse ;
Returns the nth Fibonacci number. This assumes I can leave garbage on the stack (the result is still on top), 30 bytes:
: f 1 0 rot 0 DO 2dup + LOOP ;
Ruby (as function) 31 bytes
->n{a,b=1,0;n.times{a=b+b=a};b}
Cylon (Non-Competing), 12 bytes
The language is in development, Im just putting this up here.
1:øÌ[:ì+Á])r
An explanation:
1 ;pushes a 1 to the stack
: ;duplicates the top of the stack
ø ;reads a number from stdin, pushing it to the stack
Ì ;non-pushing loop, doesn't push counter to the stack, but deletes it
[ ;start of function, to be pushed to the stack
: ;duplicate top of stack
ì ;rotate the stack, moving the copy to the back
+ ;replaces top two objects on the stack with their sum
Á ;push the result to the shadowing stack (non-consuming)
] ;end of function
) ;switch to shadowed stack
r ;standard library call, reverses a stack
;stack implicitly printed
Python, 75 bytes
a=[1,1]
while True:
a.append(a[-1]+a[-2])
a.pop(0)
print(a[-2])
Yes, I know, way too big, but I don't know golfing languages that well.
Detour (non-competing), 8 bytes
[$<<]!S.
This one is shorter than the word "fibonacci"
[$<<]!S.
Fibonacci
explanation:
[ ] # while n > 0
$<< # replace n with [n-1, n-2]
!S. # invert, output
Just for fun, here's one that will always take exactly 19 ticks to terminate, whether given 0 or 1474. On my really old macbook, it on average terminates after 7ms.
Detour, 30 28 bytes
$Q{G<!d}seQ
.{5Vg>d}se-$G_c!
Try it online!
This is the way of expressing (((1+sqrt(5))/2)^n-((1-sqrt(5))/2)^n)/sqrt(5)
Old way:
Detour (non-competing), 10 9 bytes
<Q>S.
;$<
This is non-competing: I just pushed the required version of the language about 10 minutes ago.
Detour works like befunge, fish etc. except for one crucial difference: where those languages redirect the instruction pointer, detour redirects data.
Input is pushed in at the beginning of the middle line (in this case the first). < decrements a number, > increments it. Q sends it down if a number is greater than 0, forward otherwise.
the line ;$< is the same as $<; because edges wrap. What it does is take the number it is given, then push that number and 1 less than that number to the input. This is how detour does recursion.
S reduces with addition, and . outputs the result.
For a better explanation, visit the site and it will give a visual representation of all the numbers.
Prismatic, 113 bytes (can be smaller)
right wideness wideness left forward up vertex longness backward right vertex tallness forward down vertex vertex
Inspired by Brainfuck, Cubix and Hexagony.
Java 8 29 bytes
Using Java 8 lambdas. This is a valid statement if there exists a function interface with a method that returns an int and takes an int as a parameter. Also the variable that stores the lambda must be declared as a member (static or non static) of the class it is in so that it can be used recursively.
f=n->n<2?0:f.f(n-1)+f.f(n-2);
Ungolfed:
@FunctionalInterface interface F
{
int f(int n);
}
public class Main
{
static F f;
public static void main(String[] args)
{
f=n->n<2?0:f.f(n-1)+f.f(n-2);
}
}
Ruby
Ungolfed, 60 bytes
def fib(prev,nxt)
x = prev + nxt
puts x
fib(nxt,x)
end
Golfed, 33 bytes
def f(a,b)x=a+b;puts x;f(b,x)end
Pretty simple to call, use f(first, next).
Cubix, 10 bytes
Non competing answer because the language is newer than the question.
Cubix is a new 2 dimensional language by @ETHproductions were the code is wrapped onto a cube sized to fit.
;.o.ON/+!)
This wraps onto a 2 x 2 cube in the following manner
; .
o .
O N / + ! ) . .
. . . . . . . .
. .
. .
Ooutput the value of the TOSNpush newline onto stack/reflect northooutput the character of the TOS;pop TOS/reflect east after going around the cube+add top 2 values of the stack!skip next command if TOS is 0)increment the TOS by 1. This kicks off the sequence essentially.
This is an endless loop that prints the sequence with a newline separator. It take advantage of the fact that most commands don't pop the values from the stack.
If the separator is ignored then this can be done with 5 bytes .O+!)
Hexagony, 18 14 12
Thanks Martin for 6 bytes!
1="/}.!+/M8;
Expanded:
1 = "
/ } . !
+ / M 8 ;
. . . .
. . .
Old, answer. This is being left in because the images and explanation might be helpful to new Hexagony users.
!).={!/"*10;$.[+{]
Expanded:
! ) .
= { ! /
" * 1 0 ;
$ . [ +
{ ] .
This prints the Fibonacci sequence separated by newlines.
Try it online! Be careful though, the online interpreter doesn't really like infinite output.
Explanation
There are two "subroutines" to this program, each is run by one of the two utilised IPs. The first routine prints newlines, and the second does the Fibonacci calculation and output.
The first subroutine starts on the first line and moves left to right the entire time. It first prints the value at the memory pointer (initialized to zero), and then increments the value at the memory pointer by 1. After the no-op, the IP jumps to the third line which first switches to another memory cell, then prints a newline. Since a newline has a positive value (its value is 10), the code will always jump to the fifth line, next. The fifth line returns the memory pointer to our Fibonacci number and then switches to the other subroutine. When we get back from this subroutine, the IP will jump back to the third line, after executing a no-op.
The second subroutine begins at the top right corner and begins moving Southeast. After a no-op, we are bounced to travel West along the second line. This line prints the current Fibonacci number, before moving the memory pointer to the next location. Then the IP jumps to the fourth line, where it computes the next Fibonacci number using the previous two. It then gives control back to the first subroutine, but when it regains control of the program, it continues until it meets a jump, where it bounces over the mirror that was originally used to point it West, as it returns to the second line.
Preliminary Pretty Pictures!
The left side of the image is the program, the right hand side represents the memory. The blue box is the first IP, and both IPs are pointing at the next instruction to be executed.
Note: Pictures may only appear pretty to people who have similarly limited skill with image editing programs :P I will add at least 2 more iterations so that the use of the * operator becomes more clear.
Note 2: I only saw alephalpha's answer after writing most of this, I figured it was still valuable because of the separation, but the actual Fibonacci parts of our programs are very similar. In addition, this is the smallest Hexagony program that I have seen making use of more than one IP, so I thought it might be good to keep anyway :P
Java, 71 chars
Single number: (Binet formula, considering 1.62 as the golden ratio))
int f(int n){return(Math.pow(1.62,n)-(Math.pow(-1.62,-n))/Math.sqrt(5)}
I know this isn't surprisingly short, however Math is beautiful and this formula is even more!
Cy, 33 31 30 bytes (non-competing)
This is going for the function option (takes N, outputs F(N))
0 1 :>i {1 - $&+ times} &if :<
Ungolfed/explanation:
0 1 # first two fibs are 0, 1
:>i # read input as integer (let's call it N)
{
1 -
{&+} # add the last two values
times # repeat N-1 times ^
} &if # if N is non-zero ^
:< # output the last calculated value (if N is 0, that would be 0)
Sesos, 11 bytes (non-competing)
Not in-place, linear memory.
Hexdump:
0000000: ae8583 ef6bc7 045fe7 b907 ....k.._...
Size : 11 byte(s)
Assembler
set numin
set numout
add 1,rwd 1,get ;setup tape
jmp
fwd 1
jmp,sub 1,fwd 1,add 1,fwd 1,add 1,rwd 2,jnz
rwd 1
sub 1
jmp,sub 1,fwd 1,add 1,rwd 1,jnz
fwd 1
jnz
fwd 2
put
J, 9 bytes
+/@:!&i.-
Gets the nth Fibonacci number by finding the sums of the binomial coefficients C(n-i-1, i) for i from 0 to n-1.
Also, a short way using 12 bytes to generate the first n Fibonacci numbers is
+/@(!|.)\@i.
It uses the same method as above but works by operating on prefixes of the range [0, 1, ..., n-1].
Usage
f =: +/@:!&i.-
f 10
55
f 17
1597
Explanation
+/@:!&i.- Input: n
- Negate n
&i. Form the ranges [n-1, n-2, ..., 0] and [0, 1, ..., n-1]
! Find the binomial coefficient between each pair of values
+/@: Sum those binomial coefficients and return
Maple, 27 bytes
ifelse(n<3,1,f(n-1)+f(n-2))
Usage:
> f := n -> ifelse(n<3,1,f(n-1)+f(n-2));
> f(2);
1
> f(3);
2
Julia, 20 bytes
!n=n>1?!~-n+!~-~-n:n
Straightforward implementation of the recursive definition. No match for the matrix approach, but a lovely opportunity to abuse Julia's ability to redefine operators.
Detour, 20 bytes
This one is going for the "infinite sequence" option.
v1vq:$
$+
p,p^
^ q
Branch 1 takes a number, prints it, adds it with the number from Branch 2, then puts the result in Branch 2
Branch 2 takes a number, feeds it to the addition with branch 1 then puts the original number (not the sum) in Branch 1.
For a better explanation click the link and you'll see it in action.
More "readable" version:
Detour, 267 bytes
:$v 1v q # split into branches
+ # push sum of last 2 fibonacci numbers to branch 2
{
p , p ^ # print branch 1, merge with branch 3
}
^ q # push branch 2 into branch 1 for printing and recycling
# 1 2 3
C#: 83 69 68 66 58 53 51
I used a nasty trinary and recursive lambda expression to achieve this one.
Func<ulong,ulong> f=null;f=x=>x<2?x:f(x-2)+f(x-1);
Usage:
public static void Main()
{
// Recursive lambda expression...
Func<ulong, ulong> f = null;
f = x => (x < 2) ? x : f(x - 2) + f(x - 1);
Console.WriteLine("Please enter a whole number to obtain the Fibonacci sequence number for:");
string value = Console.ReadLine();
long numValue;
if(UInt64.TryParse(value, out numValue))
Console.WriteLine(f(numValue));
Console.WriteLine("Press any key to end the program.");
Console.ReadKey();
}
PlatyPar, 7 bytes
0A1wAC+
Explanation:
0A1 ## push first two Fibonacci numbers to stack and print them
w ## while last item != 0 (always true)
A ## print the most recently calculated Fibonacci number
C+ ## push the sum of the last two items of the stack
This one is a sequence.
Python 2, 43 bytes
def f(n):k=9**n;return k**-~-~n/~-(k*~-k)%k
Fuzzy Octo Guacamole, 11 bytes
01(!aZrZo;)
This takes the infinite route.
Explanation:
01 pushes 0 and then 1 to the stack.
( starts a infinite loop.
! sets the register, saving the value on the top of the stack and storing it. It doesn't pop though.
a adds the 2 values.
ZrZ reverses the stack, pushes the register contents, and reverses again. This pushes the stored number to the bottom of the stack.
o; peeks and prints.
) ends the infinite loop.
Then the whole things starts again from the (.
As a a side note, this is quite fast to hit the max long size possible in Python. The last number it prints is 12200160415121876738, and it repeats that forever.
Alpax, 5 bytes (non-competing)
Non-competing since the language postdates the challenge. Code:
⇇+
1¹
Yes, that's right mates. My newest invention, which is more mathematically based than 05AB1E. This language uses a lot of recursion, so be aware. This is a bit like a stack based language, but a little bit different. The elaborated version of the above code is:
a(n) = ⇇+
a(0) = 1, a(1) = 1
Explanation:
⇇ is short for pushing a(n - 1), a(n - 2)
+ adds both functions up.
It then implicitly prints the result of a(n), whereas n is the input.
Uses the Alpax encoding.
Reng v.2.1, 18 bytes
(Noncompeting, postdates question)
11{:nAo}#xxx:)+x5h
11 initializes the stack with 2 1s. {:nAo}#x sets the command x to mean "duplicate and output as number" (:n) then "output a newline" (Ao, A = 10). Then, xx prints the initial 2 1s. : duplicates the TOS and ) rotates the stack, so it becomes b a b. + adds the two figures, making it b (a+b). x prints and leaves this new result on the stack. 5h jumps back 5 spaces, and the loop continues.
Scratch, 106 characters
This isn't impressive at all but someone had to do it.
when gf clicked
add[1]to[f v
forever
add((item[last v]of[f v])+(item((length of[f v])-(1))of[f v]))to[f v
Fairly bog-standard solution. "f" is a list which starts off empty. Runs as long as you let it.
Since it's not easy to define what is and isn't a "character" in Scratch I've used the forum plugin's formatting. This allows me to cheat off some additional characters (scratchblocks2 is very lenient with dropping closing parenthesis, "end"s, and shaving off whitespace here and there)
PARI/GP, 9 bytes
fibonacci
Alternate solution (21 bytes), for those disliking the built-in:
n->([1,1;1,0]^n)[1,2]
Alternate alternate solution (21 bytes):
n->imag(quadgen(5)^n)
I also posted all three solutions (in ungolfed form) to Rosetta Code's Fibonacci page.
Gogh, 10 bytes
¹Ƥ{Ƥ÷®+Ø}x
Executed from the command line like this:
$ ./gogh "" "¹Ƥ{Ƥ÷®+Ø}x"
Explanation
¹ “ Push two ones to the stack. ”
Ƥ “ Print the TOS. ”
{ “ Open a code block. ”
Ƥ “ Print the TOS. ”
÷ “ Duplicate the TOS. ”
® “ Rotate the stack leftward. ”
+ “ Destructively add the TOS to the STOS. ”
Ø “ Loop all preceding code (within the block). ”
} “ Close a code block. ”
x “ Execute the TOS. ”
Julia, 18 bytes
n->([1 1;1 0]^n)[]
DUP, 10 bytes
1$[^^+2!]!
An infinite stream that leaves results on stack. Use the Step button to avoid setting off the infinite loop.
Explanation
1$ {start w/ 2 1's}
[ ]! {execute lambda}
^^ {take top 2 items on stack}
+ {add them}
2! {self recurse!}
CJam, noncompeting, 11 bytes
0X{_@+}q~*;
JavaScript, 41 39 33 bytes
(c=(a,b)=>alert(a)+c(b,a+b))(0,1)
beeswax, 12 bytes (sequence), 42 bytes (n-th Fib.)
Beeswax is newer than the question, so no competition here.
Fibonacci sequence.
p{N<P{*
>~+d
No promotion to higher bit widths implemented in my solution, so 64-bit overflow starts at the 93rd or 92nd Fibonacci number, depending if you start counting your sequence at 0 or 1:
0
1
1
2
3
5
8
13
21
34
55
89
.
.
.
4660046610375530309
7540113804746346429
12200160415121876738 ← 93rd Fibonacci number
1293530146158671551 ← 1st. 64-bit overflow/wraparound
13493690561280548289
N-th Fibonacci number:
;{#'<>~P~L#MM@>+@'p@{;
_TNX~P~K#{; d~@M<
The same limit applies to this solution.
Lua, 51 bytes
function f(n) return n<2 and n or f(n-1)+f(n-2)end
It creates a function called f(n), that takes an input (n). If n = 1, returns n. This function uses recursion.
C, 45 bytes
Simple, iterative approach. Exits when signed integer overflows.
a;main(b){for(;b>0;printf("%d ",a=b-a))b+=a;}
Try it here.
Oracle SQL 9.2, 80 bytes
SELECT ROUND(POWER((1+SQRT(5))/2,LEVEL-1)/SQRT(5))FROM DUAL CONNECT BY LEVEL<:1;
CoffeeScript, 63 bytes
j=0;k=1;a=[];a=((i=j+k;k=j;j=i) for i in [0..prompt()]);alert a
Oration, 135 bytes
I believe that this is "optimal"... takes a deep breath here we go!
Inhale
Start a function f with n
If n<2
Return n
Backtracking
Inhale
Here
Literally, f(n-2)+f(n-1)
I'm done
Listen
Invoke f with number
The little ~> is input. This outputs the (input)th Fibonacci number. This transpiles to (in Python):
def f(n):
if n<2:
return n
return f(n-2)+f(n-1)
print(f(eval(input("~>"))))
𝔼𝕊𝕄𝕚𝕟, 3 chars / 6 bytes (noncompetitive)
Мȫï
More builtins!
math.js + numbers.js = hella functions
Brainf*ck, 489 466 characters
Granted, this is a bit overkill, not to mention that it could be optimised a lot. I will get to improving it tomorrow, since it's too late today.
EDIT: Improved by a few bytes by putting stuff closer together on the tape.
++++++>++++++++++>+>>>>>>>>>+<<<<<<<<<<<[->>[>>+>+<<<-]>>>[<<<+>
>>-]<<+>[<->[>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]+++++
+++[<++++++>-]>[<<+>>-]>[<<+>>-]<<]>]<[->>++++++++[<++++++>-]]<[
.[-]<]>>>>>>>>[->+<<<<<<<<<<+>>>>>>>>>]>[-<+>]<<<<<<<<<<<.>>>>>>
>>>>[>>+>+<<<-]>>>[<<<+>>>-]<<+>[<->[>++++++++++<[->-[>+>>]>[+[-
<+>]>+>>]<<<<<]>[-]++++++++[<++++++>-]>[<<+>>-]>[<<+>>-]<<]>]<[-
>>++++++++[<++++++>-]]<[.[-]<]<<<<<<<<<<[->+>>>>>>>>+<<<<<<<<<]>
[-<+>]<<.<]
(With added newlines for readability)
R - 39
Shortest - recursive, until SO:
f=function(i,j){cat(i);f(j,i+j)};f(1,1)
Until n:
i=j=1;for(x in 1:n){print(i);k=i;i=i+j;j=k}
or (a bit vectorized):
a=c(1,1);for(x in 1:n)print((a=c(a[2],sum(a)))[1])
or (without any loop or recursion):
a=c(1,1);sapply(1:n,function(i)a<<-c(a[2],sum(a)))[1,]
C# 4, 58 bytes
Stream (69; 65 if weakly typed to IEnumerable)
(Assuming a using directive for System.Collections.Generic.)
IEnumerable<int>F(){int c=0,n=1;for(;;){yield return c;n+=c;c=n-c;}}
Single value (58)
int F(uint n,int x=0,int y=1){return n<1?x:F(n-1,y,x+y);}
R, 40 bytes
Haven't seen a R solution, so:
f=function(n)ifelse(n<3,1,f(n-1)+f(n-2))
Ruby, 28 bytes
->f{loop{f<<p(f[-1]+f[-2])}}
Usage:
->f{loop{f<<p(f[-1]+f[-2])}}[[-1,1]]
GNU Octave: 19 chars
@(x)([1,1;1,0]^x)(1)
This solution has the distinction of running in O(log n) time.
Turing machine code, 389
I wrote this the other day and decided to post it. Generates an infinite Fibonacci sequence in unary on the tape. See a commented version in action here.
0 _ 1 r 1
1 _ _ r 2
2 _ 0 r 3
3 _ _ r 4
4 _ 0 l 5
5 0 * l 5
5 _ * l 5
5 1 * r f
a 0 1 r b
b 0 * r b
b _ * r c
c 0 * r c
c _ * r d
d _ 0 l e
e 0 * l e
e _ * l e
e 1 * r f
f 0 1 r g
f _ * r k
g 0 * r g
g _ * r h
h 0 * r h
h _ * r i
i 0 * r i
i _ 0 l j
j 0 * l j
j _ * l j
j 1 * r f
k 0 1 r l
k _ * l R
l 0 * r l
l _ * r m
m 0 * r m
m _ 0 l n
n 0 * l n
n _ * l n
n 1 * r k
R _ * r a
R 1 0 l R
Minkolang 0.10, 10 bytes
This language was created after this challenge but not for it.
Stream (link, do not click "Run"):
01d1R+dN2@
A mite clever, if I do think so. The 2@ at the end is a 2-trampoline that jumps over the 01 at the beginning, allowing the sequence to rise unabated.
Nth Fibonacci (link):
01nd,7&[d1R+]rN.
Worse than I expected, 16 bytes. 01 sets it up, nd,7&...N. prints out 0 if the input is 0 and does the loop otherwise. [d1R+] builds up the sequence, then r reverses the stack and the correct number is outputted and the program ends with N..
TeaScript, 4 bytes
F(x)
F(x) //Find the Fibonacci number at the input
Compile online here (DOES NOT WORK IN CHROME). Enter input in the first input field.
Vitsy, 11 Bytes
I'm certain there's a way to shorten these.
Print out all fibonacci (to Integer.MAX_VALUE)
01[D}+DNaO]
01 Push 0 and 1 to the stack.
[ ] Repeat infinitely.
D Duplicate the top item of the stack.
} Rotate the stack to right.
+ Add the top two items.
D Duplicate the top item.
N Print the top item out as a number.
aO Print a return.
Print out to input fibonacci (13 bytes):
01}\[D}+DNaO]
01 Push 0 and 1 to the stack.
}\[ ] Get the input and repeat that many times.
D Duplicate the top item of the stack.
} Rotate the stack to right.
+ Add the top two items.
D Duplicate the top item.
N Print the top item out as a number.
aO Print a return.
Java, 41 bytes
There are a couple other Java answers here, but I'm surprised nobody has posted this simple one:
int f(int n){return n<2?n:f(n-1)+f(n-2);}
For an extra byte you can extend the range up to long.
dc, 29 chars
1ddppsa[+sblalbsalbplxx]sxlxx
ArnoldC, 451 bytes
IT'S SHOWTIME
HEY CHRISTMAS TREE a
YOU SET US UP 1
HEY CHRISTMAS TREE b
YOU SET US UP 1
HEY CHRISTMAS TREE c
YOU SET US UP 1
STICK AROUND c
TALK TO THE HAND a
GET TO THE CHOPPER a
HERE IS MY INVITATION a
GET UP b
ENOUGH TALK
TALK TO THE HAND b
GET TO THE CHOPPER b
HERE IS MY INVITATION b
GET UP a
ENOUGH TALK
GET TO THE CHOPPER c
HERE IS MY INVITATION 1e300
LET OFF SOME STEAM BENNET a
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED
This is actually my first ArnoldC program. Horrible for golfing, but great for lolz!
Produces an stream of Fibonacci numbers up to 1.1253474885494065e+274.
Explanation
IT'S SHOWTIME #start program
HEY CHRISTMAS TREE a #declare a...
YOU SET US UP 1 #and set it to 1
HEY CHRISTMAS TREE b #declare b...
YOU SET US UP 1 #and set it to 1
HEY CHRISTMAS TREE c #declare c...
YOU SET US UP 1 #and set it to 1
STICK AROUND c #while c is truthy
TALK TO THE HAND a #output a
GET TO THE CHOPPER a #assign a to...
HERE IS MY INVITATION a #a...
GET UP b #plus b
ENOUGH TALK #end assignment
TALK TO THE HAND b #output b
GET TO THE CHOPPER b #assign b to...
HERE IS MY INVITATION b #b...
GET UP a #plus a
ENOUGH TALK #end assignment
GET TO THE CHOPPER c #assign c to...
HERE IS MY INVITATION 1e300 #whether 1e300...
LET OFF SOME STEAM BENNET a #is greater than a (returns 0 or 1)
ENOUGH TALK #end assignment
CHILL #end while
YOU HAVE BEEN TERMINATED #end program
Rust, 44 bytes
fn f(n:u8)->u8{if n<2{n}else{f(n-1)+f(n-2)}}
Javascript, 53 bytes
a=[1,1];setInterval('a.push(a[b=a.length-1]+a[b-1])')
I decided to use a new approach to create an infinite stream. Works anywhere else but Firefox.
To get the array of integers, simply do a from the console.
Python 3, 39 38 bytes
a=1
b=1
while 1:c=a+b;print(c);a=c;b=c
Ungolfed:
a = 1
b = 1
while 1:
c = a + b
print(c)
a = c
b = c
Is there some way of getting rid of the b=c statement?
Desmos, 61 bytes
Golfed
Click the add slider button for n.
p=.5+.5\sqrt{5}
n=0
f=5^{-.5}\left(p^n-\left(-p\right)^{-n}\right)
The last line is the output.
Ungolfed
Is a function.
\phi =\frac{1+\sqrt{5}}{2}
f_{ibonacci}\left(n\right)=\frac{\phi ^n-\left(-\phi \right)^{-n}}{\sqrt{5}}
Ruby - 49 characters
Nobody has done a Ruby solution for the second problem so I thought I'd give that a go:
p Hash.new{|h,k|k<2?k:(h[k-2]+h[k-1])}[gets.to_i]
TI-BASIC, 11
By legendary TI-BASIC golfer Kenneth Hammond ("Weregoose"), from this site. Runs in O(1) time, and considers 0 to be the 0th term of the Fibonacci sequence.
int(round(√(.8)cosh(Anssinh‾¹(.5
To use:
2:int(round(√(.8)cosh(Anssinh‾¹(.5
1
12:int(round(√(.8)cosh(Anssinh‾¹(.5
144
How does this work? If you do the math, it turns out that sinh‾¹(.5) is equal to ln φ, so it's a modified version of Binet's formula that rounds down instead of using the (1/φ)^n correction term. The round( (round to 9 decimal places) is needed to prevent rounding errors.
Julia - 20 Characters
f=n->([1 1;1 0]^n)[]
I used the same basic algorithm as the Octave answer. This starts with f(0)->1, f(1)->1, to avoid needing an explicit array index. This is 4 characters shorter than the naive recursive algorithm.
f=n->n<2?1:f(n-1)+f(n-2)
Octave, 26 chars
f=@(n)([1 0]*[1 1;1 0]^n)(2)
Basically, a copy of my solution from Calculating (3 + sqrt(5))^n exactly.
![[a b] x [1 1 ;1 0] equals [a+b a]](https://i.sstatic.net/gKY9a.gif)
, so
![[f(1) f(0)] x [1 1 ;1 0]^n equals [f(n+1) f(n)]](https://i.sstatic.net/5TCJa.gif)
It's a disaster to do unnecessary* loops in Octave/Matlab. It's neither elegant, nor fast, let alone golfy.
*All loops that can be vectorized are unnecessary :).
Prelude, 12 bytes
One of the few challenges where Prelude is actually fairly competitive:
1(v!v)
^+^
This requires the Python interpreter which prints values as decimal numbers instead of characters.
Explanation
In Prelude, all lines are executed in parallel, with the instruction pointer traversing columns of the program. Each line has its own stack which is initialised to zero.
1(v!v)
^+^
| Push a 1 onto the first stack.
| Start a loop from here to the closing ).
| Copy the top value from the first stack to the second and vice-versa.
| Print the value on the first stack, add the top two numbers on the second stack.
| Copy the top value from the first stack to the second and vice-versa.
The loop repeats forever, because the first stack will never have a 0 on top.
Note that this starts the Fibonacci sequence from 0.
JAGL V1.0 - 13 / 11
1d{cdc+dcPd}u
Infinite Fibonacci sequence. Or, if not required to print:
11 bytes
1d{cdc+cd}u
Ruby, 27
What, no Ruby answers?
p a=b=1;loop{a,b=(p b),a+b}
Prints each number, starting correctly with the first two 1s, to STDOUT ad infinitum (VERY QUICKLY from irb in my environment - you've been warned). I've been learning Ruby lately, so I figured I'd contribute this. If it can be shortened in any way, let me know.
TI-BASIC - 18 symbols
to print fibonacci sequence starting from 0:
;i
;While 1
;Disp real(Ans
;real(Ans)+imag(Ans)+ireal(Ans
;End
to print fibonacci sequence starting from 1:
;1
;While 1
;Disp real(Ans
;real(Ans)+imag(Ans)+ireal(Ans
;End
Perl 6, 10 chars:
Anonymous infinite fibonacci sequence list:
^2,*+*...*
Same as:
0, 1, -> $x, $y { $x + $y } ... Inf;
So, you can assign it to an array:
my @short-fibs = ^2, * + * ... *;
or
my @fibs = 0, 1, -> $x, $y { $x + $y } ... Inf;
And get the first eleven values (from 0 to 10) with:
say @short-fibs[^11];
or with:
say @fibs[^11];
Wait, you can get too the first 50 numbers from anonymous list itself:
say (^2,*+*...*)[^50]
That returns:
0 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
And some simple benchmark:
real 0m0.966s
user 0m0.842s
sys 0m0.080s
With:
$ time perl6 -e 'say (^2, *+* ... *)[^50]'
EOF
Befunge 98, 10 characters
1:"]"y+#
8-character code generating the fibonacci sequence on the stack, under the assumption that # should first wrap around then skip, which sadly does not hold in CCBI (where I run my Befunge code). It would work if we restricted the fungespace X dimension to 8 cells.
1#;:"]"y+;
Using 10 characters, the code actually works in CCBI, generating the sequence on the stack.
1#;:.:"]"y+;
With 12 characters, we have working code that outputs space-delimited numbers to stdout (would be 10 chars if based on the first version).
1#;:.:"]"y+:0`2*k#@;
This 20-character version ends the loop as soon as overflow occurs (on 32bit system, it delivers the sequence up to 1836311903). If you add 2 more characters, each number is on a separate line (insert a, after :.)
All these versions operate purely on the stack, no modification of fungespace cells. The 'printing' versions do so in addition to generating the sequence on the stack.
Breakdown:
1pushes 1 on the empty stack.#skips the next fungespace cell (;).:.duplicates, pops and prints the top-of-stack value (1 in the first iteration). Insertinga,here outputs an ASCII 10 character, which makes a new line.:duplicates again. (Stack now [1 1])"]"pushes 93 (ASCII). This is explained further below. (Stack now [1 1 93])ypops a value and pushes system information for it. In our case, that's the third-of-top value on the stack. In the first iteration, this is 0, as there are only two elements there. (Stack now [1 1 0])+pops two values and pushes their sum. (Stack now [1 1]):0'compares the TOS value with 0 and pushes 1 if it was greater, else 0. (It should be a backtick.) (Stack now [1 1 1])2*k#pops and doubles our comparison result, and performs the#that many times (0 or 2). While the numbers are positive, it skips to the;, otherwise to the@(becausekautomatically moves the IP beyond its target with a 0 argument). (Stack now [1 1])@terminates the program. It is only reached when overflow occurred.;creates kind of a wormhole. It skips everything until it encounters another;, which it will at the third character of the line. Execution continues with step 3.)
In step 5.), I use 93 as an argument to y. This value is individual, because y outputs things like the command line arguments and environment variables, and starts returning values from the stack (top-down) if its argument is greater than the size of actual system information y emits. If eg. you rename the script to a different length name, you have to adjust this value.
To find the correct value, you can insert 01-y (which pushes ALL system information) at the beginning, start in the debugger (-t switch for CCBI), step 4, see how big your stack is, add 3, and replace ] with the resulting character.
Note that the use of y may cause CCBI to report an Access violation on @ which can be safely ignored, as is the case on my system (Win8.1/64, ccbi.exe/32). The short versions keep on looping into eternity (given infinite memory).
PS: If we move the :. between the y and +, the printed sequence becomes 0 1 1 2 ...
If we want it starting with 0 on the stack, we simply insert 0 at the beginning (and leave :. where it is now).
~-~! (No Comment) - 27
'=|*>~[<'&*-~>+<'&*-~~>]*|:
Didn't think it'd be this short.
Forth - 38 33 bytes
: f dup . 2dup + 2 pick recurse ;
Generates and prints a Fibonacci series recursively until it runs out of stack space.
Usage:
1 1 f
Or to generate Fn, where n>=1 (66 bytes):
: f dup 3 < if 1 nip else dup 1- recurse swap 2 - recurse + then ;
Example of usage:
9 f .
output:
34
F#, 63 chars:
let rec g x y n=if n=x then x else f (n-1) y (x+y)
let f=g 0 1
C 64 Characters
a;main(f,n){scanf("%d",&n);while(--n)f+=a=f-a;printf("%d",f-a);}
This will print the nth Fibonacci number.
A more readable format :
a;
main(f,n){
scanf("%d",&n);
while(--n)
f+=a=f-a;
printf("%d",f-a);
}
COW, 108
MoO moO MoO mOo MOO OOM MMM moO moO
MMM mOo mOo moO MMM mOo MMM moO moO
MOO MOo mOo MoO moO moo mOo mOo moo
PowerShell: 42 or 75
Find nth Fibonacci number - 42
A spin-off of Joey's answer, this will take user input and output the nth Fibonacci number. This retains some weaknesses also inherent to Joey's original code:
- Technically off by 1, since it starts the Fibonacci sequence at
1,1instead of the more proper0,1.- Only valid for Fibonacci numbers which will fit into int32, because this is PowerShell's default type for integers.
- Example: Due to the int32 limitation, the highest input that will return a valid report is 46 (1,836,311,903) and this is technically the 47th Fibonacci number since zero was skipped.
Golfed:
($b=1)..(read-host)|%{$a,$b=$b,($a+$b)};$a
Un-Golfed & Commented:
# Feed integers, from 1 to a user-input number, into a ForEach-Object loop.
# Initialize $b while we're at it.
($b=1)..(read-host)|%{
# Using multiple variable assignment...
# ...current $b is put into new $a, and...
# ...sum of current $b and current $a are put into new $b.
$a,$b=$b,($a+$b)
};
# When loop exits, output $a.
$a
# Variable cleanup, not included in golfed code.
rv a,b
List Fibonacci numbers - 75
Another derivative of Joey's answer, but with some improvements:
- Zero is included in the output, as it should be according to OEIS.
- Goes up to the maximum Fibonacci number that can be handled as uint64 instead of the default int32. (Highest Fibonacci number in uint64 is 12,200,160,415,121,876,738.)
- Output stops once the maximum value is reached, instead of looping through 'Infinity' or continuously throwing errors.
Golfed:
for($a,$b=0,1;$a+$b-le[uint64]::MaxValue){$a;$a,$b=$b,[uint64]($a+$b)}$a;$b
Un-Golfed & Commented:
# Start Fibonacci loop.
for
(
# Begin with $a and $b at zero and one.
$a,$b=0,1;
# Continue so long as the sum fits in uint64.
$a+$b-le[uint64]::MaxValue
)
{
# Output current $a.
$a;
# Using multiple variable assignment...
# ...current $b becomes new $a, and...
# ...sum of current $b and current $a is forced to uint64 and stored in new $b.
$a,$b=$b,[uint64]($a+$b)
}
# Output $a and $b one more time.
$a;$b
# Variable cleanup - not included in golfed code.
rv a,b
Befunge, 15 13 characters
1:.:00p+00g\#
I didn't spot any Befunge solutions, so I thought I'd write one. Too bad Befunge doesn't have a rotate-n operation, and trampoline . Turns out that part of the spec is considered ambiguous on that point, and my initial interpretation is actually valid.# doesn't work at end-of-line to skip first character after looping around
FAC: Functional APL, 4 characters (!!)
Not mine, therefore posted as community wiki. FAC is a dialect of APL that Hai-Chen Tu apparently suggested as his PhD dissertation in 1985. He later wrote an article together with Alan J. Perlis called "FAC: A Functional APL Language". This dialect of APL uses "lazy arrays" and allow for arrays of infinite length. It defines an operator "iter" (⌼) to allow for compact definition of some recursive sequences.
The monadic ("unary") case of ⌼ is basically Haskell's iterate, and is defined as (F⌼) A ≡ A, (F A), (F (F A)), …. The dyadic ("binary") case is defined somewhat analogously for two variables: A (F⌼) B ≡ A, B, (A F B), (B F (A F B)), …. Why is this useful? Well, as it turns out this is precisely the kind of recurrence the Fibonacci sequence has. In fact, one of the examples given of it is
1+⌼1
producing the familiar sequence 1 1 2 3 5 8 ….
So, there you go, quite possibly the shortest possible Fibonacci implementation in a non-novelty programming language. :D
BrainFuck, 172 characters
>++++++++++>+>+[[+++++[>++++++++<-]>.<++++++[>--------<-]+<<<]>.>>[[-]<[>+<-]>>[<<+>+>-]<[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>+<-[>[-]>+>+<<<-[>+<-]]]]]]]]]]]+>>>]<<<]
Credit goes to Daniel Cristofani
C, 45 (37)
Only because it's easy:
f(n){return n<2?n?1:0:f(n-1)+f(n-2);}
Or the more compiler-friendly/standards-compliant but more verbose version:
#define m main(n
m){return n<2?n?1:0:m-1)+m-2);}
note: once compiled, you have to call main() with an actual value (which will likely take some command line fiddling depending on OS)
F# - 42 chars
Seq.unfold(fun(a,b)->Some(a,(b,a+b)))(0,1)
JAVA - 108 characters:
int[]f={0,1};System.out.println(0);for(int i=0;i<9;i+=2)System.out.printf("%d\n%d\n",f[0]+=f[1],f[1]+=f[0]);
Windows PowerShell – 34 30
for($b=1){$a,$b=$b,($a+$b)
$a}
C#: 38 (40 to ensure non-negative numbers)
Inspired by the beauty of Jon Skeet's C# answer and St0le's answer, another C# solution in only 38 characters:
Func<int,int>f=n=>n>2?f(n-1)+f(n-2):1;
Tested with:
for(int i = 1; i <= 15; i++)
Console.WriteLine(f(i));
Yay for recursive Func<>! Incorrect when you pass in negative numbers, however - corrected by the 40 character version, which doesn't accept them:
Func<uint,uint>f=n=>n>2?f(n-1)+f(n-2):1;
Note: as pointed out by @Andrew Gray, this solution doesn't work in Visual Studio, as the compiler rejects the in-line function definition referring to itself. The Mono compiler at http://www.compileonline.com/compile_csharp_online.php, however, runs it just fine. :)

Visual Studio: 45
Func<int,int>f=null;f=n=>n>2?f(n-1)+f(n-2):1;
Mathematica,26 chars
If[#>1,#0[#-1]+#0[#-2],#]&
APL: 26 characters
This is a function which will print out the n and n-1 Fibonacci numbers:
{({⍵+.×2 2⍴1 1 1 0}⍣⍵)0 1}
For example,
{({⍵+.×2 2⍴1 1 1 0}⍣⍵)0 1}13
yields the vector:
233 144
C: 48 47 characters
A really really truly ugly thing. It recursively calls main, and spits out warnings in any sane compiler. But since it compiles under both Clang and GCC, without any odd arguments, I call it a success.
b;main(a){printf("%u ",b+=a);if(b>0)main(b-a);}
It prints numbers from the Fibonacci sequence until the integers overflow, and then it continues spitting out ugly negative and positve numbers until it segfaults. Everything happens in well under a second.
Now it actually behaves quite well. It prints numbers from the Fibonacci sequence and stops when the integers overflow, but since it prints them as unsigned you never see the overflow:
VIC-20:~ Fors$ ./fib
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 VIC-20:~ Fors$
Haskell: 27 (21) characters
It almost feels like cheating to use Haskell for something like this. It just prints Fibonacci numbers ad infinitum.
f=1:scanl(+)1f
main=print f
And if using GHCi only 21 characters, including two newlines, are necessary:
Prelude>let f=1:scanl(+)1f
Prelude>f
[1,1,2,3,5,8,13,21...
Clojure, 46
(defn f[x y z](if(= 0 z)x(recur y(+ y x)(- z 1))))
Although, technically 50 since Clojure requires the recur for pseudo tail call:
(defn f[x y z](if(= 0 z)x(recur y(+ y x)(- z 1))))
Non compressed:
(defn fib [left right iteration]
(if (= 0 iteration)
left
(fib right (+ right left) (- iteration 1))))
Python 3 (53)
def f(n):
l,p=0,1
while n:n,l,p=n-1,p,l+p
return l
C#
Generated as a stream (65 chars):
IEnumerable<int>F(){for(int c=1,s=1;;){s+=c=s-c;yield return c;}}
Could be reduced to 61 characters using non-generic IEnumerable. Of course, if you include the required System.Collections.Generic, then it's a few more characters.
Mathematica, 9 chars
Fibonacci
If built-in functions are not allowed, here's an explicit solution:
Mathematica, 33 32 31 chars
#&@@Nest[{+##,#}&@@#&,{0,1},#]&
J, 10 chars
Using built-in calculation of Taylor series coefficients so maybe little cheaty. Learned it here.
(%-.-*:)t.
(%-.-*:)t. 0 1 2 3 4 5 10 100
0 1 1 2 3 5 55 354224848179261915075
MATLAB/Octave, n first numbers, 41 39 chars
a=0:1;for(i=3:n);a(i)=a(i-2)+a(i-1);end
Javascript - 48 chars
for(i=1;i<n;i++){f[i]=f[i-1]+(f[i-2]?f[i-2]:0);}
Clean and simple... probably not a shortness winner :D
Here is the full implementation:
function a(n) {
var i;
var f = new Array();
f[0]=1;
for(i=1;i<n;i++){f[i]=f[i-1]+(f[i-2]?f[i-2]:0);}
console.log(f);
}
Perl - 39 chars
($a,$b)=($b,$a+$b||1),print"$b
"while$=
PHP - 109 97 88 49 characters
<?for($a=$b++;;$b+=$a=$b-$a){$s+=$b%2*$b;echo$a;}
Clojure: 38 chars
(def f(lazy-cat[0 1](map +(rest f)f)))
run with:
f
PHP, Finite - 46 chars
<?for($b=1;$i++<$n;)echo$b-$a=($b+=$a)-$a,"
";
where $n is the length of the sequence
PHP, Infinite - 39 chars
<?for($b=1;;)echo$b-$a=($b+=$a)-$a,"
";
Python (56 chars)
n=input()
x=5**0.5
print ((1+x)**n-(1-x)**n)/((2**n)*x)
And for the sequence
n=input()
i=1
x=5**0.5
while i<=n:
print ((1+x)**i-(1-x)**i)/((2**i)*x)
i+=1
C / Objective-c, 62
c;f(a,b){printf("%d ",a+b);if(c++<40)f(a+b,a);}main(){f(0,1);}
This will print the first 40 fibonacci numbers. I assume the compiler will set c=0. If it is trash, than it will not work;
This version is smaller, but it infite show all sequence number
C / Objective-c, 50 (infinite)
f(a,b){printf("%d ",a+b);f(a+b,a);}main(){f(0,1);}
Perl, 51 (Loopless)
The following code uses Binet's formula to give the Nth Fibonacci number without using any loops.
print((($p=5**.5/2+.5)**($n=<>)-(-1/$p)**$n)/5**.5)
Python O(1) Nth number, 91 char
48 characters for the import, a newline, 42 for the rest. I know it's longer than most here and that the question is a bit old, but I looked through the answers and I didn't see any that use the constant-time floating-point calculation.
from math import trunc as t,pow as p,sqrt as s
r=s(5);i=(1+r)/2;f=lambda n:t(p(i,n)/r+.5)
From there you call f(n) for the nth number in the sequence. Eventually it loses precision, and is only accurate up through f(70) (190,392,490,709,135). i is the constant Phi.
CHIP 8
Not so short but displays the fibonacci sequence on screen:
00E06600690060006101221E3900120E8200801081206F00810489F0120A6500830064F083428336833683368336F32900E0D56575088300640F8342F329D56500EE
without displaying on screen:
00E06000610182008010812081041206
Scala, 52 chars:
def f(a:Int,b:Int):Int={println(a);f(b,a+b)};f(0,1)
Python, 34 chars first variant, 31 chars for second variant,
a,b=1,1
while 1:print a;a,b=b,a+b
Second variant:
f=lambda x:x<2 or f(x-2)+f(x-1)
Common Lisp, 48 Chars
(defun f(n)(if(< n 2) n(+(f(decf n))(f(1- n)))))
bc, 36 chars
r=0;l=1;while(i++<99){r+=l;l+=r;r;l}
K - 12
Calculates the n and n-1 Fibonacci number.
{x(|+\)/0 1}
Just the nth Fibonacci number.
{*x(|+\)/0 1}
Ruby, 25 chars
st0le's answer shortened.
p 1,a=b=1;loop{p b=a+a=b}
Golfscript - single number - 12/11/10
12 chars for taking input from stdin:
~0 1@{.@+}*;
11 chars for input already on the stack:
0 1@{.@+}*;
10 chars for further defining 1 as the 0th Fibonacci number:
1.@{.@+}*;
DC (20 bytes)
As a bonus, it's even obfuscated ;)
zzr[dsb+lbrplax]dsax
EDIT: I may point out that it prints all the numbers in the fibonacci sequence, if you wait long enough.
J - 20
First n terms:
(+/@(2&{.),])^:n i.2
Bash 100
This is a very slow, but hey no performance penalty. First line needed.
#!/bin/bash
if [ $1 -lt 2 ]; then
echo $1; exit; fi
expr `$0 \`expr $1 - 1\`` + `$0 \`expr $1 - 2\``
GolfScript, 12
Now, just 12 characters!
1.{.@.p+.}do
Python
a,b,n=0,1,10
while n:a,b,n=b,a+b,n-1;print b
Python, 36
f=lambda x:x>1and f(x-1)+f(x-2)or x


















