Javascript required
Skip to content Skip to sidebar Skip to footer

Find Nth Fibonacci Number Java O Logn Solution

Task

Fibonacci sequence
You are encouraged to solve this task according to the task description, using any language you may know.

The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:

                                    F0              = 0                                                          F1              = 1                                                          Fn              = Fn-1              + Fn-2, if n>1                              
Task

Write a function to generate the nth Fibonacci number.

Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).

The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:

                                    Fn              = Fn+2              - Fn+1, if n<0                              

support for negative n in the solution is optional.

Related tasks
  • Fibonacci n-step number sequences‎
  • Leonardo numbers
References
  • Wikipedia, Fibonacci number
  • Wikipedia, Lucas number
  • MathWorld, Fibonacci Number
  • Some identities for r-Fibonacci numbers
  • OEIS Fibonacci numbers
  • OEIS Lucas numbers

Contents

  • 1 0815
  • 2 11l
  • 3 360 Assembly
    • 3.1 using fullword integers
    • 3.2 using packed decimals
  • 4 6502 Assembly
  • 5 8080 Assembly
  • 6 8th
  • 7 ABAP
    • 7.1 Iterative
    • 7.2 Impure Functional
  • 8 ACL2
  • 9 Action!
  • 10 ActionScript
  • 11 Ada
    • 11.1 Recursive
    • 11.2 Iterative, build-in integers
    • 11.3 Iterative, long integers
    • 11.4 Fast method using fast matrix exponentiation
  • 12 AdvPL
    • 12.1 Recursive
    • 12.2 Iterative
  • 13 Aime
  • 14 ALGOL 60
  • 15 ALGOL 68
    • 15.1 Analytic
    • 15.2 Iterative
    • 15.3 Recursive
    • 15.4 Generative
    • 15.5 Array (Table) Lookup
  • 16 ALGOL W
  • 17 ALGOL-M
    • 17.1 Iterative
    • 17.2 Naively recursive
  • 18 Alore
  • 19 AntLang
  • 20 Apex
  • 21 APL
    • 21.1 Naive Recursive
    • 21.2 Array
    • 21.3 Analytic
  • 22 AppleScript
    • 22.1 Imperative
    • 22.2 Functional
  • 23 Arendelle
  • 24 ARM Assembly
  • 25 ArnoldC
  • 26 Arturo
    • 26.1 Recursive
  • 27 AsciiDots
  • 28 ATS
    • 28.1 Recursive
    • 28.2 Iterative
    • 28.3 Iterative and Verified
    • 28.4 Matrix-based
  • 29 AutoHotkey
    • 29.1 Iterative
    • 29.2 Recursive and iterative
  • 30 AutoIt
    • 30.1 Iterative
    • 30.2 Recursive
  • 31 AWK
  • 32 Axe
  • 33 Babel
  • 34 bash
    • 34.1 Iterative
    • 34.2 Recursive
  • 35 BASIC
    • 35.1 Applesoft BASIC
    • 35.2 BASIC256
    • 35.3 Commodore BASIC
    • 35.4 Integer BASIC
    • 35.5 IS-BASIC
    • 35.6 QBasic
      • 35.6.1 Iterative
      • 35.6.2 Recursive
      • 35.6.3 Array (Table) Lookup
      • 35.6.4 Fibonacci from Russia
    • 35.7 Sinclair ZX81 BASIC
      • 35.7.1 Analytic
      • 35.7.2 Iterative
      • 35.7.3 Tail recursive
  • 36 Batch File
  • 37 Battlestar
  • 38 BBC BASIC
  • 39 bc
    • 39.1 iterative
  • 40 BCPL
  • 41 beeswax
  • 42 Befunge
  • 43 Bracmat
    • 43.1 Recursive
    • 43.2 Iterative
  • 44 Brainf***
  • 45 Brat
    • 45.1 Recursive
    • 45.2 Tail Recursive
    • 45.3 Memoization
  • 46 Burlesque
  • 47 C
    • 47.1 Recursive
    • 47.2 Iterative
    • 47.3 Analytic
    • 47.4 Generative
    • 47.5 Fast method for a single large value
  • 48 C#
    • 48.1 Recursive
    • 48.2 Tail-Recursive
    • 48.3 Iterative
    • 48.4 Eager-Generative
    • 48.5 Lazy-Generative
    • 48.6 Analytic
    • 48.7 Matrix
    • 48.8 Array (Table) Lookup
    • 48.9 Arbitrary Precision
  • 49 C++
    • 49.1 Using Zeckendorf Numbers
    • 49.2 Using Standard Template Library
  • 50 Cat
  • 51 Chapel
  • 52 Chef
  • 53 Clio
  • 54 Clojure
    • 54.1 Lazy Sequence
    • 54.2 Iterative
    • 54.3 Doubling Algorithm (Fast)
    • 54.4 Recursive
    • 54.5 Using core.async
  • 55 CLU
  • 56 CMake
  • 57 COBOL
    • 57.1 Iterative
    • 57.2 Recursive
  • 58 CoffeeScript
    • 58.1 Analytic
    • 58.2 Iterative
    • 58.3 Recursive
  • 59 Comefrom0x10
    • 59.1 Iterative
  • 60 Common Lisp
    • 60.1 Iterative
    • 60.2 Recursive
    • 60.3 Alternate solution
    • 60.4 Solution with methods and eql specializers
    • 60.5 List-based iterative
    • 60.6 List-based recursive
  • 61 Computer/zero Assembly
  • 62 Corescript
  • 63 Cowgol
  • 64 Crystal
    • 64.1 Recursive
    • 64.2 Iterative
    • 64.3 Tail Recursive
    • 64.4 Analytic
  • 65 D
    • 65.1 Matrix Exponentiation Version
    • 65.2 Faster Version
  • 66 Dart
  • 67 Datalog
  • 68 DBL
  • 69 Dc
  • 70 Delphi
    • 70.1 Iterative
    • 70.2 Recursive
    • 70.3 Matrix
  • 71 DIBOL-11
  • 72 DWScript
  • 73 Dyalect
  • 74 E
  • 75 EasyLang
  • 76 EchoLisp
  • 77 ECL
    • 77.1 Analytic
  • 78 EDSAC order code
  • 79 Eiffel
  • 80 Ela
  • 81 Elena
    • 81.1 Alternative version using yieldable method
  • 82 Elixir
  • 83 Elm
  • 84 Emacs Lisp
    • 84.1 version 1
    • 84.2 version 2
  • 85 Erlang
    • 85.1 Recursive
    • 85.2 Iterative
    • 85.3 Iterative 2
  • 86 ERRE
  • 87 Euphoria
    • 87.1 'Recursive' version
    • 87.2 'Iterative' version
    • 87.3 'Tail recursive' version
    • 87.4 'Paper tape' version
  • 88 Excel
    • 88.1 LAMBDA
  • 89 F#
  • 90 Factor
    • 90.1 Iterative
    • 90.2 Recursive
    • 90.3 Tail-Recursive
    • 90.4 Matrix
  • 91 Falcon
    • 91.1 Iterative
    • 91.2 Recursive
    • 91.3 Tail Recursive
  • 92 FALSE
  • 93 Fancy
  • 94 Fantom
  • 95 Fermat
  • 96 Fexl
  • 97 FOCAL
  • 98 Forth
  • 99 Fortran
    • 99.1 FORTRAN IV
    • 99.2 FORTRAN 77
    • 99.3 Recursive
    • 99.4 Iterative
  • 100 Free Pascal
  • 101 FreeBASIC
  • 102 Frink
  • 103 FRISC Assembly
  • 104 FunL
    • 104.1 Recursive
    • 104.2 Tail Recursive
    • 104.3 Lazy List
    • 104.4 Iterative
    • 104.5 Binet's Formula
    • 104.6 Matrix Exponentiation
  • 105 Futhark
    • 105.1 Iterative
  • 106 FutureBasic
    • 106.1 Iterative
  • 107 Fōrmulæ
  • 108 GAP
  • 109 Gecho
  • 110 GFA Basic
  • 111 GML
  • 112 Go
    • 112.1 Recursive
    • 112.2 Iterative
    • 112.3 Iterative using a closure
    • 112.4 Using a goroutine and channel
  • 113 Groovy
    • 113.1 Recursive
    • 113.2 Iterative
    • 113.3 Analytic
  • 114 Harbour
    • 114.1 Recursive
    • 114.2 Iterative
  • 115 Haskell
    • 115.1 Analytic
    • 115.2 Recursive
    • 115.3 Recursive with Memoization
    • 115.4 Recursive with Memoization using memoized library
    • 115.5 Iterative
      • 115.5.1 With lazy lists
      • 115.5.2 As a fold
    • 115.6 With matrix exponentiation
    • 115.7 With recurrence relations
  • 116 Haxe
    • 116.1 Iterative
    • 116.2 As Iterator
  • 117 HicEst
  • 118 Hoon
  • 119 Hope
    • 119.1 Recursive
    • 119.2 Tail-recursive
    • 119.3 With lazy lists
  • 120 Hy
  • 121 Icon and Unicon
  • 122 IDL
    • 122.1 Recursive
    • 122.2 Iterative
    • 122.3 Analytic
  • 123 Idris
    • 123.1 Analytic
    • 123.2 Recursive
    • 123.3 Iterative
    • 123.4 Lazy
  • 124 J
  • 125 Java
    • 125.1 Iterative
    • 125.2 Recursive
    • 125.3 Caching-recursive
    • 125.4 Analytic
    • 125.5 Tail-recursive
    • 125.6 Streams
  • 126 JavaScript
    • 126.1 ES5
      • 126.1.1 Recursive
    • 126.2 Iterative
      • 126.2.1 Memoization
      • 126.2.2 Y-Combinator
      • 126.2.3 Generators
    • 126.3 ES6
      • 126.3.1 Memoized
  • 127 Joy
    • 127.1 Recursive
    • 127.2 Iterative
  • 128 jq
    • 128.1 Recursive
    • 128.2 Tail Recursive
    • 128.3 Binet's Formula
    • 128.4 Generator
  • 129 Julia
    • 129.1 Recursive
    • 129.2 Iterative
    • 129.3 Matrix form
  • 130 K
    • 130.1 Recursive
    • 130.2 Recursive with memoization
    • 130.3 Analytic
    • 130.4 Sequence to n
  • 131 Kabap
    • 131.1 Sequence to n
  • 132 Klingphix
  • 133 Kotlin
  • 134 L++
  • 135 LabVIEW
  • 136 lambdatalk
  • 137 Lang5
  • 138 langur
  • 139 Lasso
  • 140 Latitude
    • 140.1 Recursive
    • 140.2 Memoization
  • 141 Lean
  • 142 LFE
    • 142.1 Recursive
    • 142.2 Iterative
  • 143 Liberty BASIC
    • 143.1 Iterative/Recursive
    • 143.2 Iterative/Negative
  • 144 Lingo
    • 144.1 Recursive
    • 144.2 Iterative
    • 144.3 Analytic
  • 145 Lisaac
  • 146 LiveCode
  • 147 LLVM
  • 148 Logo
  • 149 LOLCODE
  • 150 LSL
  • 151 Lua
    • 151.1 Recursive
    • 151.2 Pedantic Recursive
    • 151.3 Tail Recursive
    • 151.4 Table Recursive
    • 151.5 Table Recursive 2
    • 151.6 Iterative
  • 152 Luck
  • 153 Lush
  • 154 M2000 Interpreter
  • 155 M4
  • 156 MAD
  • 157 Maple
  • 158 Mathematica / Wolfram Language
  • 159 MATLAB
    • 159.1 Matrix
    • 159.2 Iterative
    • 159.3 Dramadah Matrix Method
    • 159.4 Tartaglia/Pascal Triangle Method
  • 160 Maxima
  • 161 MAXScript
    • 161.1 Iterative
    • 161.2 Recursive
  • 162 Mercury
    • 162.1 fib.m
    • 162.2 Iterative algorithm
    • 162.3 Memoization
  • 163 Metafont
  • 164 Microsoft Small Basic
    • 164.1 Iterative
    • 164.2 Binet's Formula
  • 165 min
  • 166 MiniScript
  • 167 MIPS Assembly
  • 168 Mirah
  • 169 МК-61/52
  • 170 ML
    • 170.1 Standard ML
      • 170.1.1 Tail Recursion
      • 170.1.2 Recursion
    • 170.2 MLite
      • 170.2.1 Recursion
  • 171 ML/I
  • 172 Modula-2
  • 173 Modula-3
    • 173.1 Recursive
    • 173.2 Iterative (with negatives)
  • 174 Monicelli
  • 175 MontiLang
  • 176 MUMPS
    • 176.1 Iterative
  • 177 Nanoquery
    • 177.1 Iterative
  • 178 Nemerle
    • 178.1 Recursive
    • 178.2 Tail Recursive
  • 179 NESL
    • 179.1 Recursive
  • 180 NetRexx
  • 181 NewLISP
    • 181.1 Iterative
    • 181.2 Recursive
    • 181.3 Matrix multiplication
    • 181.4 With a stack
  • 182 NGS
    • 182.1 Iterative
  • 183 Nial
    • 183.1 Iterative
    • 183.2 Recursive
    • 183.3 Matrix
  • 184 Nim
    • 184.1 Analytic
    • 184.2 Iterative
    • 184.3 Recursive
    • 184.4 Tail-recursive
    • 184.5 Continuations
  • 185 Nix
  • 186 Oberon-2
  • 187 Objeck
    • 187.1 Recursive
  • 188 Objective-C
    • 188.1 Recursive
    • 188.2 Iterative
  • 189 OCaml
    • 189.1 Iterative
    • 189.2 Recursive
    • 189.3 Arbitrary Precision
    • 189.4 O(log(n)) with arbitrary precision
  • 190 Octave
    • 190.1 Recursive
    • 190.2 Iterative
    • 190.3 Analytic
    • 190.4 Tail Recursive
  • 191 Oforth
  • 192 Ol
  • 193 OPL
  • 194 Order
    • 194.1 Recursive
    • 194.2 Memoization
  • 195 Oz
    • 195.1 Iterative
    • 195.2 Recursive
    • 195.3 Tail-recursive
    • 195.4 Lazy-recursive
  • 196 PARI/GP
    • 196.1 Built-in
    • 196.2 Matrix
    • 196.3 Analytic
    • 196.4 Algebraic
    • 196.5 Combinatorial
    • 196.6 Binary powering
    • 196.7 Recursive
    • 196.8 Anonymous recursion
    • 196.9 Memoization
    • 196.10 Iterative
    • 196.11 Chebyshev
    • 196.12 Anti-Hadamard matrix
    • 196.13 Testing adjacent bits
    • 196.14 One-by-one
  • 197 Pascal
    • 197.1 Analytic
    • 197.2 Recursive
    • 197.3 Iterative
    • 197.4 Analytic2
  • 198 Perl
    • 198.1 Iterative
    • 198.2 Recursive
    • 198.3 Modules
  • 199 Phix
  • 200 Phixmonti
  • 201 PHP
    • 201.1 Iterative
    • 201.2 Recursive
  • 202 PicoLisp
    • 202.1 Recursive
    • 202.2 Recursive with Cache
    • 202.3 Iterative
    • 202.4 Coroutines
  • 203 Pike
    • 203.1 Iterative
    • 203.2 Recursive
  • 204 PIR
  • 205 PL/I
  • 206 PL/M
  • 207 PL/pgSQL
    • 207.1 Recursive
    • 207.2 Calculated
    • 207.3 Linear
    • 207.4 Tail recursive
  • 208 PL/SQL
  • 209 Plain English
  • 210 Pop11
  • 211 PostScript
  • 212 Potion
    • 212.1 Recursive
    • 212.2 Iterative
    • 212.3 Matrix based
    • 212.4 Handling negative values
  • 213 PowerBASIC
  • 214 PowerShell
    • 214.1 Iterative
    • 214.2 Recursive
  • 215 Processing
  • 216 Prolog
    • 216.1 Poor man's memoization
    • 216.2 Continuation passing style
    • 216.3 With lazy lists
    • 216.4 Generators idiom
    • 216.5 Yet another implementation
    • 216.6 Efficient implementation
  • 217 Pure
    • 217.1 Tail Recursive
  • 218 PureBasic
    • 218.1 Macro based calculation
    • 218.2 Recursive
    • 218.3 Recursive & optimized with a static hash table
  • 219 Purity
  • 220 Python
    • 220.1 Analytic
    • 220.2 Iterative
      • 220.2.1 Iterative positive and negative
    • 220.3 Recursive
    • 220.4 Recursive with Memoization
    • 220.5 Better Recursive doesn't need Memoization
    • 220.6 Generative
      • 220.6.1 Example use
    • 220.7 Matrix-Based
    • 220.8 Large step recurrence
    • 220.9 Same as above but slightly faster
    • 220.10 Generative with Recursion
    • 220.11 As a scan or a fold
      • 220.11.1 itertools.accumulate
      • 220.11.2 functools.reduce
    • 220.12 Array and Range
  • 221 QB64
  • 222 Qi
    • 222.1 Recursive
    • 222.2 Iterative
  • 223 Quackery
  • 224 R
    • 224.1 Iterative positive and negative
    • 224.2 Other methods
  • 225 Ra
  • 226 Racket
    • 226.1 Tail Recursive
    • 226.2 Matrix Form
  • 227 Raku
    • 227.1 List Generator
    • 227.2 Iterative
    • 227.3 Recursive
  • 228 RASEL
  • 229 Red
  • 230 Relation
  • 231 Retro
    • 231.1 Recursive
    • 231.2 Iterative
  • 232 REXX
  • 233 Ring
  • 234 Rockstar
    • 234.1 Iterative (minimized)
    • 234.2 Iterative (idiomatic)
    • 234.3 Recursive
  • 235 Ruby
    • 235.1 Iterative
    • 235.2 Recursive
    • 235.3 Recursive with Memoization
    • 235.4 Matrix
    • 235.5 Generative
    • 235.6 Binet's Formula
  • 236 Run BASIC
  • 237 Rust
    • 237.1 Iterative
    • 237.2 Recursive
    • 237.3 Recursive (with pattern matching)
    • 237.4 Tail recursive (with pattern matching)
    • 237.5 Analytic
    • 237.6 Using an Iterator
      • 237.6.1 Iterator "Successors"
  • 238 S-BASIC
  • 239 SAS
    • 239.1 Iterative
    • 239.2 Naive recursive
  • 240 Sather
  • 241 Scala
    • 241.1 Recursive
    • 241.2 Lazy sequence
    • 241.3 Tail recursive
    • 241.4 foldLeft
    • 241.5 Iterator
  • 242 Scheme
    • 242.1 Iterative
    • 242.2 Recursive
    • 242.3 Recursive Sequence Generator
    • 242.4 Dijkstra Algorithm
  • 243 Scilab
  • 244 sed
  • 245 Seed7
    • 245.1 Recursive
    • 245.2 Iterative
  • 246 SequenceL
    • 246.1 Recursive
    • 246.2 Tail Recursive
    • 246.3 Matrix
  • 247 SETL
  • 248 Shen
  • 249 Sidef
    • 249.1 Iterative
    • 249.2 Recursive
    • 249.3 Recursive with memoization
    • 249.4 Closed-form
    • 249.5 Built-in
  • 250 Simula
  • 251 SkookumScript
    • 251.1 Built-in
    • 251.2 Recursive
    • 251.3 Iterative
  • 252 Slate
  • 253 Smalltalk
  • 254 smart BASIC
  • 255 SNOBOL4
    • 255.1 Recursive
    • 255.2 Tail-recursive
    • 255.3 Iterative
    • 255.4 Analytic
  • 256 SNUSP
    • 256.1 Iterative
    • 256.2 Recursive
  • 257 Softbridge BASIC
    • 257.1 Iterative
  • 258 Spin
    • 258.1 Iterative
  • 259 SPL
    • 259.1 Analytic
    • 259.2 Iterative
    • 259.3 Recursive
  • 260 SQL
    • 260.1 Analytic
    • 260.2 Recursive
  • 261 SSEM
  • 262 Stata
    • 262.1 Mata
  • 263 StreamIt
  • 264 SuperCollider
    • 264.1 Recursive
    • 264.2 Analytic
    • 264.3 Iterative
  • 265 Swift
    • 265.1 Analytic
    • 265.2 Iterative
    • 265.3 Recursive
  • 266 Tailspin
    • 266.1 Recursive simple
    • 266.2 Iterative, mutable state
    • 266.3 State machine
  • 267 Tcl
    • 267.1 Simple Version
      • 267.1.1 Iterative
      • 267.1.2 Recursive
      • 267.1.3 Tail-Recursive
    • 267.2 Handling Negative Numbers
      • 267.2.1 Iterative
      • 267.2.2 Recursive
    • 267.3 For the Mathematically Inclined
  • 268 Tern
    • 268.1 Recursive
    • 268.2 Coroutine
  • 269 TI-83 BASIC
  • 270 TI-89 BASIC
    • 270.1 Recursive
    • 270.2 Iterative
  • 271 Tiny BASIC
  • 272 TSE SAL
  • 273 Turing
  • 274 TUSCRIPT
  • 275 UNIX Shell
  • 276 UnixPipes
  • 277 Ursa
    • 277.1 Iterative
  • 278 Ursala
  • 279 V
  • 280 Vala
    • 280.1 Recursive
    • 280.2 Iterative
  • 281 VAX Assembly
  • 282 VBA
  • 283 VBScript
    • 283.1 Non-recursive, object oriented, generator
      • 283.1.1 Class Definition:
      • 283.1.2 Invocation:
      • 283.1.3 Output:
  • 284 Vedit macro language
    • 284.1 Iterative
    • 284.2 Unlimited precision
  • 285 Visual Basic
  • 286 Visual Basic .NET
    • 286.1 Iterative
    • 286.2 Recursive
    • 286.3 BigInteger
    • 286.4 BigInteger, speedier method
  • 287 Vlang
    • 287.1 Iterative
    • 287.2 Recursive
  • 288 Wart
    • 288.1 Recursive, all at once
    • 288.2 Recursive, using cases
    • 288.3 Recursive, using memoization
  • 289 WDTE
    • 289.1 Memoized Recursive
    • 289.2 Iterative
  • 290 WebAssembly
  • 291 Whitespace
    • 291.1 Iterative
    • 291.2 Recursive
  • 292 Wrapl
    • 292.1 Generator
    • 292.2 Iterator
  • 293 Wren
  • 294 x86 Assembly
  • 295 xEec
  • 296 XLISP
    • 296.1 Analytic
    • 296.2 Tail recursive
  • 297 Xojo
  • 298 XPL0
  • 299 XQuery
  • 300 zkl
  • 301 ZX Spectrum Basic
    • 301.1 Iterative
    • 301.2 Analytic

0815 [edit]


%<:0D:>~$<:01:~%>=<:a94fad42221f2702:>~>
}:_s:{x{={~$x+%{=>~>x~-x<:0D:~>~>~^:_s:?

11l [edit]

Translation of: Python

F fib_iter(n)
I n < 2
R n
V fib_prev = 1
V fib = 1
L 2 .< n
(fib_prev, fib) = (fib, fib + fib_prev)
R fib

 L(i) 1..20
print(fib_iter(i), end' ' ')
print()

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765        

360 Assembly [edit]

For maximum compatibility, programs use only the basic instruction set.

using fullword integers [edit]

*        Fibonacci sequence    05/11/2014
* integer (31 bits) = 10 decimals -> max fibo(46)
FIBONACC CSECT
USING FIBONACC,R12 base register
SAVEAREA B STM-SAVEAREA(R15) skip savearea
DC 17F'0' savearea
DC CL8'FIBONACC' eyecatcher
STM STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R12,R15 set addressability
* ----
LA R1,0 f(n-2)=0
LA R2,1 f(n-1)=1
LA R4,2 n=2
LA R6,1 step
LH R7,NN limit
LOOP EQU * for n=2 to nn
LR R3,R2 f(n)=f(n-1)
AR R3,R1 f(n)=f(n-1)+f(n-2)
CVD R4,PW n convert binary to packed (PL8)
UNPK ZW,PW packed (PL8) to zoned (ZL16)
MVC CW,ZW zoned (ZL16) to char (CL16)
OI CW+L'CW-1,X'F0' zap sign
MVC WTOBUF+5(2),CW+14 output
CVD R3,PW f(n) binary to packed decimal (PL8)
MVC ZN,EM load mask
ED ZN,PW packed dec (PL8) to char (CL20)
MVC WTOBUF+9(14),ZN+6 output
WTO MF=(E,WTOMSG) write buffer
LR R1,R2 f(n-2)=f(n-1)
LR R2,R3 f(n-1)=f(n)
BXLE R4,R6,LOOP endfor n
* ----
LM R14,R12,12(R13) restore previous savearea pointer
XR R15,R15 return code set to 0
BR R14 return to caller
* ---- DATA
NN DC H'46' nn max n
PW DS PL8 15num
ZW DS ZL16
CW DS CL16
ZN DS CL20
* ' b 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0' 15num
EM DC XL20'402020206B2020206B2020206B2020206B202120' mask
WTOMSG DS 0F
DC H'80',XL2'0000'
* fibo(46)=1836311903
WTOBUF DC CL80'fibo(12)=1234567890'
REGEQU
END FIBONACC
... fibo(41)=   165,580,141 fibo(42)=   267,914,296 fibo(43)=   433,494,437 fibo(44)=   701,408,733 fibo(45)= 1,134,903,170 fibo(46)= 1,836,311,903        

using packed decimals [edit]

*        Fibonacci sequence        31/07/2018
* packed dec (PL8) = 15 decimals => max fibo(73)
FIBOWTOP CSECT
USING FIBOWTOP,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
SAVE (14,12) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
* ----
ZAP FNM2,=P'0' f(0)=0
ZAP FNM1,=P'1' f(1)=1
LA R4,2 n=2
LA R6,1 step
LH R7,NN limit
LOOP EQU * for n=2 to nn
ZAP FN,FNM1 f(n)=f(n-2)
AP FN,FNM2 f(n)=f(n-1)+f(n-2)
CVD R4,PW n
MVC ZN,EM load mask
ED ZN,PW packed dec (PL8) to char (CL16)
MVC WTOBUF+5(2),ZN+L'ZN-2 output
MVC ZN,EM load mask
ED ZN,FN packed dec (PL8) to char (CL16)
MVC WTOBUF+9(L'ZN),ZN output
WTO MF=(E,WTOMSG) write buffer
ZAP FNM2,FNM1 f(n-2)=f(n-1)
ZAP FNM1,FN f(n-1)=f(n)
BXLE R4,R6,LOOP endfor n
* ----
L R13,4(0,R13) restore previous savearea pointer
RETURN (14,12),RC=0 restore registers from calling sav
* ---- DATA
NN DC H'73' nn
FNM2 DS PL8 f(n-2)
FNM1 DS PL8 f(n-1)
FN DS PL8 f(n)
PW DS PL8 15num
ZN DS CL20
* ' b 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0 , 0 0 0' 15num
EM DC XL20'402020206B2020206B2020206B2020206B202120' mask
WTOMSG DS 0F
DC H'80',XL2'0000'
* fibo(73)=806515533049393
WTOBUF DC CL80'fibo(12)=123456789012345 '
REGEQU
END FIBOWTOP
... fibo(68)=  72,723,460,248,141 fibo(69)= 117,669,030,460,994 fibo(70)= 190,392,490,709,135 fibo(71)= 308,061,521,170,129 fibo(72)= 498,454,011,879,264 fibo(73)= 806,515,533,049,393        

6502 Assembly [edit]

This subroutine stores the first n—by default the first ten—Fibonacci numbers in memory, beginning (because, why not?) at address 3867 decimal = F1B hex. Intermediate results are stored in three sequential addresses within the low 256 bytes of memory, which are the most economical to access.

The results are calculated and stored, but are not output to the screen or any other physical device: how to do that would depend on the hardware and the operating system.

          LDA  #0
STA $F0  ; LOWER NUMBER
LDA #1
STA $F1  ; HIGHER NUMBER
LDX #0
LOOP: LDA $F1
STA $0F1B,X
STA $F2  ; OLD HIGHER NUMBER
ADC $F0
STA $F1  ; NEW HIGHER NUMBER
LDA $F2
STA $F0  ; NEW LOWER NUMBER
INX
CPX #$0A  ; STOP AT FIB(10)
BMI LOOP
RTS  ; RETURN FROM SUBROUTINE

8080 Assembly [edit]

This subroutine expects to be called with the value of n {\displaystyle n} in register A, and returns f ( n ) {\displaystyle f(n)} also in A. You may want to take steps to save the previous contents of B, C, and D. The routine only works with fairly small values of n {\displaystyle n} .

FIBNCI: MOV  C,  A  ; C will store the counter
DCR C  ; decrement, because we know f(1) already
MVI A, 1
MVI B, 0
LOOP: MOV D, A
ADD B  ; A := A + B
MOV B, D
DCR C
JNZ LOOP  ; jump if not zero
RET  ; return from subroutine

8th [edit]

An iterative solution:


: fibon \ n -- fib(n)
>r 0 1
( tuck n:+ ) \ fib(n-2) fib(n-1) -- fib(n-1) fib(n)
r> n:1- times ;

 : fib \ n -- fib(n)
dup 1 n:= if 1 ;; then
fibon nip ;

ABAP [edit]

Iterative [edit]

          FORM          fibonacci_iter          USING          index          TYPE          i
CHANGING number_fib TYPE i.
DATA : lv_old type i,
lv_cur type i.
Do index times .
If sy- index = 1 or sy- index = 2 .
lv_cur = 1 .
lv_old = 0 .
endif .
number_fib = lv_cur + lv_old.
lv_old = lv_cur.
lv_cur = number_fib.
enddo .
ENDFORM .

Impure Functional [edit]

Works with: ABAP version 7.4 SP08 Or above only

cl_demo_output=>          display          (          REDUCE #(          INIT fibnm          =          VALUE          stringtab(          (          |0|          )          (          |1|          )          )          
n TYPE string
x = `0`
y = `1`
FOR i = 1 WHILE i <= 100
NEXT n = ( x + y )
fibnm = VALUE #( BASE fibnm ( n ) )
x = y
y = n ) ) .

ACL2 [edit]

Fast, tail recursive solution:

          (          defun          fast-fib-r          (n a b)          
( if ( or (zp n) (zp ( 1- n) ) )
b
(fast-fib-r ( 1- n) b (+ a b) ) ) )

( defun fast-fib (n)
(fast-fib-r n 1 1 ) )

( defun first-fibs-r (n i)
(declare (xargs : measure (nfix (- n i) ) ) )
( if (zp (- n i) )
nil
( cons (fast-fib i)
(first-fibs-r n ( 1+ i) ) ) ) )

( defun first-fibs (n)
(first-fibs-r n 0 ) )

>(first-fibs 20) (1 1 2 3 5 8 13 21 34 55 89    144 233 377 610 987 1597 2584 4181 6765)        

Action! [edit]

Action! language does not support recursion. Therefore an iterative approach has been proposed.

INT FUNC Fibonacci(INT n)
INT curr,prev,tmp

  IF n>=-1 AND n<=1 THEN
RETURN (n)
FI

  prev=0
IF n>0 THEN
curr=1
DO
tmp=prev
prev=curr
curr==+tmp
n==-1
UNTIL n=1
OD
ELSE
curr=-1
DO
tmp=prev
prev=curr
curr==+tmp
n==+1
UNTIL n=-1
OD
FI
RETURN (curr)

 PROC Main()
BYTE n
INT f

  Put(125) ;clear screen

  FOR n=0 TO 22
DO
f=Fibonacci(n)
Position(2,n+1)
PrintF("Fib(%I)=%I",n,f)

  IF n>0 THEN
f=Fibonacci(-n)
Position(21,n+1)
PrintF("Fib(%I)=%I",-n,f)
FI
OD
RETURN

Screenshot from Atari 8-bit computer

Fib(0)=0 Fib(1)=1           Fib(-1)=-1 Fib(2)=1           Fib(-2)=-1 Fib(3)=2           Fib(-3)=-2 Fib(4)=3           Fib(-4)=-3 Fib(5)=5           Fib(-5)=-5 Fib(6)=8           Fib(-6)=-8 Fib(7)=13          Fib(-7)=-13 Fib(8)=21          Fib(-8)=-21 Fib(9)=34          Fib(-9)=-34 Fib(10)=55         Fib(-10)=-55 Fib(11)=89         Fib(-11)=-89 Fib(12)=144        Fib(-12)=-144 Fib(13)=233        Fib(-13)=-233 Fib(14)=377        Fib(-14)=-377 Fib(15)=610        Fib(-15)=-610 Fib(16)=987        Fib(-16)=-987 Fib(17)=1597       Fib(-17)=-1597 Fib(18)=2584       Fib(-18)=-2584 Fib(19)=4181       Fib(-19)=-4181 Fib(20)=6765       Fib(-20)=-6765 Fib(21)=10946      Fib(-21)=-10946 Fib(22)=17711      Fib(-22)=-17711        

ActionScript [edit]

          public          function          fib(n:uint):uint
{
if (n < 2 )
return n;

  return fib(n - 1 ) + fib(n - 2 );
}

Ada [edit]

Recursive [edit]

          with          Ada.Text_IO, Ada.Command_Line;

procedure Fib is

  X: Positive := Positive'Value(Ada.Command_Line.Argument ( 1 ) );

  function Fib(P: Positive) return Positive is
begin
if P <= 2 then
return 1;
else
return Fib(P-1 ) + Fib(P-2 );
end if;
end Fib;

begin
Ada.Text_IO.Put ( "Fibonacci(" & Integer'Image(X) & " ) = " );
Ada.Text_IO.Put_Line (Integer'Image(Fib(X) ) );
end Fib;

Iterative, build-in integers [edit]

          with          Ada.Text_IO;          use          Ada.Text_IO;

procedure Test_Fibonacci is
function Fibonacci (N : Natural) return Natural is
This : Natural := 0;
That : Natural := 1;
Sum  : Natural;
begin
for I in 1..N loop
Sum  := This + That;
That := This;
This := Sum;
end loop;
return This;
end Fibonacci;
begin
for N in 0..10 loop
Put_Line (Positive'Image (Fibonacci (N) ) );
end loop;
end Test_Fibonacci;

          0  1  1  2  3  5  8  13  21  34  55        

Iterative, long integers [edit]

Using the big integer implementation from a cryptographic library [1].

          with          Ada.Text_IO, Ada.Command_Line, Crypto.Types.Big_Numbers;

procedure Fibonacci is

  X: Positive := Positive'Value(Ada.Command_Line.Argument ( 1 ) );

  Bit_Length: Positive := 1 + ( 696 * X) / 1000;
-- that number of bits is sufficient to store the full result.

  package LN is new Crypto.Types.Big_Numbers
(Bit_Length + ( 32 - Bit_Length mod 32 ) );
-- the actual number of bits has to be a multiple of 32
use LN;

  function Fib(P: Positive) return Big_Unsigned is
Previous: Big_Unsigned := Big_Unsigned_Zero;
Result: Big_Unsigned := Big_Unsigned_One;
Tmp: Big_Unsigned;
begin
-- Result = 1 = Fibonacci(1)
for I in 1 .. P-1 loop
Tmp := Result;
Result := Previous + Result;
Previous := Tmp;
-- Result = Fibonacci(I+1))
end loop;
return Result;
end Fib;

begin
Ada.Text_IO.Put ( "Fibonacci(" & Integer'Image(X) & " ) = " );
Ada.Text_IO.Put_Line (LN.Utils.To_String (Fib(X) ) );
end Fibonacci;

> ./fibonacci 777 Fibonacci( 777 ) = 1081213530912648191985419587942084110095342850438593857649766278346130479286685742885693301250359913460718567974798268702550329302771992851392180275594318434818082

Fast method using fast matrix exponentiation [edit]


with ada.text_io;
use ada.text_io;

procedure fast_fibo is
-- We work with biggest natural integers in a 64 bits machine
type Big_Int is mod 2**64;

  -- We provide an index type for accessing the fibonacci sequence terms
type Index is new Big_Int;

  -- fibo is a generic function that needs a modulus type since it will return
-- the n'th term of the fibonacci sequence modulus this type (use Big_Int to get the
-- expected behaviour in this particular task)
generic
type ring_element is mod <>;
with function "*" (a, b : ring_element) return ring_element is <>;
function fibo (n : Index) return ring_element;
function fibo (n : Index) return ring_element is

  type matrix is array ( 1 .. 2, 1 .. 2 ) of ring_element;

  -- f is the matrix you apply to a column containing (F_n, F_{n+1}) to get
-- the next one containing (F_{n+1},F_{n+2})
-- could be a more general matrix (given as a generic parameter) to deal with
-- other linear sequences of order 2
f : constant matrix := ( 1 => ( 0, 1 ), 2 => ( 1, 1 ) );

  function "*" (a, b : matrix) return matrix is
( 1 => (a( 1,1 )*b( 1,1 )+a( 1,2 )*b( 2,1 ), a( 1,1 )*b( 1,2 )+a( 1,2 )*b( 2,2 ) ),
2 => (a( 2,1 )*b( 1,1 )+a( 2,2 )*b( 2,1 ), a( 2,1 )*b( 1,2 )+a( 2,2 )*b( 2,2 ) ) );

  function square (m : matrix) return matrix is (m * m);

  -- Fast_Pow could be non recursive but it doesn't really matter since
-- the number of calls is bounded up by the size (in bits) of Big_Int (e.g 64)
function fast_pow (m : matrix; n : Index) return matrix is
( if n = 0 then ( 1 => ( 1, 0 ), 2 => ( 0, 1 ) ) -- = identity matrix
elsif n mod 2 = 0 then square (fast_pow (m, n / 2 ) )
else m * square (fast_pow (m, n / 2 ) ) );

  begin
return fast_pow (f, n) ( 2, 1 );
end fibo;

  function Big_Int_Fibo is new fibo (Big_Int);
begin
-- calculate instantly F_n with n=10^15 (modulus 2^64 )
put_line (Big_Int_Fibo ( 10**15 )'img);
end fast_fibo;

AdvPL [edit]

Recursive [edit]


#include "totvs.ch"
User Function fibb(a,b,n)
return(if(--n>0,fibb(b,a+b,n),a))

Iterative [edit]


#include "totvs.ch"
User Function fibb(n)
local fnow:=0, fnext:=1, tempf
while (--n>0)
tempf:=fnow+fnext
fnow:=fnext
fnext:=tempf
end while
return(fnext)

Aime [edit]

integer
fibs(integer n)
{
integer w;

  if (n == 0) {
w = 0;
} elif (n == 1) {
w = 1;
} else {
integer a, b, i;

  i = 1;
a = 0;
b = 1;
while (i < n) {
w = a + b;
a = b;
b = w;
i += 1;
}
}

  return w;
}

ALGOL 60 [edit]

Works with: A60

begin
comment Fibonacci sequence;
integer procedure fibonacci(n); value n; integer n;
begin
integer i, fn, fn1, fn2;
fn2 := 1;
fn1 := 0;
fn  := 0;
for i := 1 step 1 until n do begin
fn  := fn1 + fn2;
fn2 := fn1;
fn1 := fn
end;
fibonacci := fn
end fibonacci;

  integer i;
for i := 0 step 1 until 20 do outinteger(1,fibonacci(i))
end

          0  1  1  2  3  5  8  13  21  34  55  89  144  233  377  610  987  1597  2584  4181  6765        

ALGOL 68 [edit]

Analytic [edit]

Works with: ALGOL 68 version Revision 1 - no extensions to language used

Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d

          PROC          analytic fibonacci          =          (          LONG          INT          n)          LONG          INT          :          (          
LONG REAL sqrt 5 = long sqrt (5) ;
LONG REAL p = (1 + sqrt 5) / 2;
LONG REAL q = 1/p;
ROUND ( (p**n + q**n) / sqrt 5 )
) ;

FOR i FROM 1 TO 30 WHILE
print ( whole (analytic fibonacci(i) ,0) ) ;
# WHILE # i /= 30 DO
print ( ", " )
OD ;
print ( new line )

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        

Iterative [edit]

Works with: ALGOL 68 version Revision 1 - no extensions to language used

Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d

          PROC          iterative fibonacci          =          (          INT          n)          INT          :          
CASE n+1 IN
0, 1, 1, 2, 3, 5
OUT
INT even:=3, odd:=5;
FOR i FROM odd+1 TO n DO
( ODD i|odd|even) := odd + even
OD ;
( ODD n|odd|even)
ESAC ;

FOR i FROM 0 TO 30 WHILE
print ( whole (iterative fibonacci(i) ,0) ) ;
# WHILE # i /= 30 DO
print ( ", " )
OD ;
print ( new line )

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        

Recursive [edit]

Works with: ALGOL 68 version Revision 1 - no extensions to language used

Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d

          PROC          recursive fibonacci          =          (          INT          n)          INT          :          
( n < 2 | n | fib(n-1) + fib(n-2) ) ;

Generative [edit]

Translation of: Python – Note: This specimen retains the original Python coding style.

Works with: ALGOL 68 version Revision 1 - no extensions to language used

Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d

          MODE          YIELDINT          =          PROC          (          INT          )          VOID          ;          

PROC gen fibonacci = ( INT n, YIELDINT yield) VOID : (
INT even:=0, odd:=1;
yield(even) ;
yield(odd) ;
FOR i FROM odd+1 TO n DO
yield( ( ODD i|odd|even) := odd + even )
OD
) ;

 main: (
# FOR INT n IN # gen fibonacci(30, # ) DO ( #
## ( INT n) VOID : (
print ( ( " " , whole (n,0) ) )
# OD # ) ) ;
print ( new line )
)

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        

Array (Table) Lookup [edit]

Works with: ALGOL 68 version Revision 1 - no extensions to language used

Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d

This uses a pre-generated list, requiring much less run-time processor usage, but assumes that INT is only 31 bits wide.

          [          ]          INT          const fibonacci          =          [          ]          INT          (          -1836311903,          1134903170,          
-701408733, 433494437, -267914296, 165580141, -102334155,
63245986, -39088169, 24157817, -14930352, 9227465, -5702887,
3524578, -2178309, 1346269, -832040, 514229, -317811, 196418,
-121393, 75025, -46368, 28657, -17711, 10946, -6765, 4181,
-2584, 1597, -987, 610, -377, 233, -144, 89, -55, 34, -21, 13,
-8, 5, -3, 2, -1, 1, 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
) [ @-46] ;

PROC VOID value error := stop;

PROC lookup fibonacci = ( INT i) INT : (
IF LWB const fibonacci <= i AND i<= UPB const fibonacci THEN
const fibonacci[i]
ELSE
value error; SKIP
FI
) ;

FOR i FROM 0 TO 30 WHILE
print ( whole (lookup fibonacci(i) ,0) ) ;
# WHILE # i /= 30 DO
print ( ", " )
OD ;
print ( new line )

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        

ALGOL W [edit]

begin
% return the nth Fibonacci number %
integer procedure Fibonacci( integer value n ) ;
begin
integer fn, fn1, fn2;
fn2 := 1;
fn1 := 0;
fn  := 0;
for i := 1 until n do begin
fn  := fn1 + fn2;
fn2 := fn1;
fn1 := fn
end ;
fn
end Fibonacci ;

  for i := 0 until 10 do writeon( i_w := 3, s_w := 0, Fibonacci( i ) )

 end.

          0  1  1  2  3  5  8 13 21 34 55        

ALGOL-M [edit]

Note that the 21st Fibonacci number (= 10946) is the largest that can be calculated without overflowing ALGOL-M's integer data type.

Iterative [edit]

INTEGER FUNCTION FIBONACCI( X ); INTEGER X;
BEGIN
INTEGER M, N, A, I;
M := 0;
N := 1;
FOR I := 2 STEP 1 UNTIL X DO
BEGIN
A := N;
N := M + N;
M := A;
END;
FIBONACCI := N;
END;

Naively recursive [edit]

INTEGER FUNCTION FIBONACCI( X ); INTEGER X;
BEGIN
IF X < 3 THEN
FIBONACCI := 1
ELSE
FIBONACCI := FIBONACCI( X - 2 ) + FIBONACCI( X - 1 );
END;

Alore [edit]

def fib(n as Int) as Int
if n < 2
return 1
end
return fib(n-1) + fib(n-2)
end

AntLang [edit]

/Sequence
fib:{<0;1> {x,<x[-1]+x[-2]>}/ range[x]}
/nth
fibn:{fib[x][x]}

Apex [edit]


/*
author: snugsfbay
date: March 3, 2016
description: Create a list of x numbers in the Fibonacci sequence.
- user may specify the length of the list
- enforces a minimum of 2 numbers in the sequence because any fewer is not a sequence
- enforces a maximum of 47 because further values are too large for integer data type
- Fibonacci sequence always starts with 0 and 1 by definition
*/
public class FibNumbers{

 final static Integer MIN = 2; //minimum length of sequence
final static Integer MAX = 47; //maximum length of sequence

 /*
description: method to create a list of numbers in the Fibonacci sequence
param: user specified integer representing length of sequence should be 2-47, inclusive.
- Sequence starts with 0 and 1 by definition so the minimum length could be as low as 2.
- For 48th number in sequence or greater, code would require a Long data type rather than an Integer.
return: list of integers in sequence.
*/
public static List<Integer> makeSeq(Integer len){

  List<Integer> fib = new List<Integer>{0,1}; // initialize list with first two values
Integer i;

  if(len<MIN || len==null || len>MAX) {
if (len>MAX){
len=MAX; //set length to maximum if user entered too high a value
}else{
len=MIN; //set length to minimum if user entered too low a value or none
}
} //This could be refactored using teneray operator, but we want code coverage to be reflected for each condition

  //start with initial list size to find previous two values in the sequence, continue incrementing until list reaches user defined length
for(i=fib.size(); i<len; i++){
fib.add(fib[i-1]+fib[i-2]); //create new number based on previous numbers and add that to the list
}

  return fib;
}

 }

APL [edit]

Naive Recursive [edit]


fib←{⍵≤1:⍵ ⋄ (∇ ⍵-1)+∇ ⍵-2}

Read this as: In the variable "fib", store the function that says, if the argument is less than or equal to 1, return the argument. Else, calculate the value you get when you recursively call the current function with the argument of the current argument minus one and add that to the value you get when you recursively call the current function with the argument of the current function minus two.

This naive solution requires Dyalog APL because GNU APL does not support this syntax for conditional guards.

Array [edit]

Since APL is an array language we'll use the following identity:

( 1 1 1 0 ) n = ( F n + 1 F n F n F n 1 ) . {\displaystyle {\begin{pmatrix}1&1\\1&0\end{pmatrix}}^{n}={\begin{pmatrix}F_{n+1}&F_{n}\\F_{n}&F_{n-1}\end{pmatrix}}.}

In APL:


↑+.×/N/⊂2 2⍴1 1 1 0

Plugging in 4 for N gives the following result:

( 5 3 3 2 ) {\displaystyle {\begin{pmatrix}5&3\\3&2\end{pmatrix}}}

Here's what happens: We replicate the 2-by-2 matrix N times and then apply inner product-replication. The First removes the shell from the Enclose. At this point we're basically done, but we need to pick out only F n {\displaystyle F_{n}} in order to complete the task. Here's one way:


↑0 1↓↑+.×/N/⊂2 2⍴1 1 1 0

Analytic [edit]

An alternative approach, using Binet's formula (which was apparently known long before Binet):

⌊.5+(((1+PHI)÷2)*⍳N)÷PHI←5*.5

AppleScript [edit]

Imperative [edit]

          set          fibs          to          {          }          
set x to ( text returned of ( display dialog "What fibbonaci number do you want?" default answer "3" ) )
set x to x as integer
repeat with y from 1 to x
if (y = 1 or y = 2 ) then
copy 1 to the end of fibs
else
copy ( ( item (y - 1 ) of fibs) + ( item (y - 2 ) of fibs) ) to the end of fibs
end if
end repeat
return item x of fibs

Functional [edit]

The simple recursive version is famously slow:

          on          fib(n)          
if n < 1 then
0
else if n < 3 then
1
else
fib(n - 2 ) + fib(n - 1 )
end if
end fib

but we can combine enumFromTo(m, n) with the accumulator of a higher-order fold/reduce function to memoize the series:

Translation of: JavaScript

(ES6 memoized fold example)

Translation of: Haskell

(Memoized fold example)

          -------------------- FIBONACCI SEQUENCE --------------------          

-- fib :: Int -> Int
on fib(n)

  -- lastTwo : (Int, Int) -> (Int, Int)
script lastTwo
on |λ|( [a, b] )
[b, a + b]
end |λ|
end script

  item 1 of foldl(lastTwo, { 0, 1 }, enumFromTo( 1, n) )
end fib

 --------------------------- TEST ---------------------------
on run

  fib( 32 )

  --> 2178309
end run

-------------------- GENERIC FUNCTIONS ---------------------

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m ≤ n then
set lst to { }
repeat with i from m to n
set end of lst to i
end repeat
lst
else
{ }
end if
end enumFromTo

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn

2178309

Arendelle [edit]

( fibonacci , 1; 1 )  [ 98 , // 100 numbers of fibonacci  	( fibonacci[ @fibonacci? ] ,  		@fibonacci[ @fibonacci - 1 ] + @fibonacci[ @fibonacci - 2 ]  	)  	"Index: | @fibonacci? | => | @fibonacci[ @fibonacci? - 1 ] |" ]

ARM Assembly [edit]

Expects to be called with n {\displaystyle n} in R0, and will return f ( n ) {\displaystyle f(n)} in the same register.

fibonacci:
push {r1-r3}
mov r1, #0
mov r2, #1

 fibloop:
mov r3, r2
add r2, r1, r2
mov r1, r3
sub r0, r0, #1
cmp r0, #1
bne fibloop

  mov r0, r2
pop {r1-r3}
mov pc, lr

ArnoldC [edit]

IT'S SHOWTIME

 HEY CHRISTMAS TREE f1
YOU SET US UP @I LIED
TALK TO THE HAND f1

 HEY CHRISTMAS TREE f2
YOU SET US UP @NO PROBLEMO

 HEY CHRISTMAS TREE f3
YOU SET US UP @I LIED

 STICK AROUND @NO PROBLEMO

 GET TO THE CHOPPER f3
HERE IS MY INVITATION f1
GET UP f2
ENOUGH TALK
TALK TO THE HAND f3

 GET TO THE CHOPPER f1
HERE IS MY INVITATION f2
ENOUGH TALK

 GET TO THE CHOPPER f2
HERE IS MY INVITATION f3
ENOUGH TALK

 CHILL

 YOU HAVE BEEN TERMINATED

Arturo [edit]

Recursive [edit]

fib: $[x][
if? x<2 [1]
else [(fib x-1) + (fib x-2)]
]

 loop 1..25 [x][
print ["Fibonacci of" x "=" fib x]
]

AsciiDots [edit]

 /--#$--\
| |
>-*>{+}/
| \+-/
1 |
# 1
| #
| |
. .

ATS [edit]

Recursive [edit]


fun fib_rec(n: int): int =
if n >= 2 then fib_rec(n-1) + fib_rec(n-2) else n

Iterative [edit]


(*
** This one is also referred to as being tail-recursive
*)
fun
fib_trec(n: int): int =
if
n > 0
then (fix loop (i:int, r0:int, r1:int): int => if i > 1 then loop (i-1, r1, r0+r1) else r1)(n, 0, 1)
else 0

Iterative and Verified [edit]


(*
** This implementation is verified!
*)

 dataprop FIB (int, int) =
| FIB0 (0, 0) | FIB1 (1, 1)
| {n:nat} {r0,r1:int} FIB2 (n+2, r0+r1) of (FIB (n, r0), FIB (n+1, r1))
// end of [FIB] // end of [dataprop]

 fun
fibats{n:nat}
(n: int (n))
: [r:int] (FIB (n, r) | int r) = let
fun loop
{i:nat | i <= n}{r0,r1:int}
(
pf0: FIB (i, r0), pf1: FIB (i+1, r1)
| ni: int (n-i), r0: int r0, r1: int r1
) : [r:int] (FIB (n, r) | int r) =
if (ni > 0)
then loop{i+1}(pf1, FIB2 (pf0, pf1) | ni - 1, r1, r0 + r1)
else (pf0 | r0)
// end of [if]
// end of [loop]
in
loop {0} (FIB0 (), FIB1 () | n, 0, 1)
end // end of [fibats]

Matrix-based [edit]


(* ****** ****** *)
//
// How to compile:
// patscc -o fib fib.dats
//
(* ****** ****** *)
//
#include
"share/atspre_staload.hats"
//
(* ****** ****** *)
//
[email protected]
int3_t0ype =
(int, int, int)
//
typedef int3 = int3_t0ype
//
(* ****** ****** *)

 extern
fun int3 : (int, int, int) -<> int3
extern
fun int3_1 : int3 -<> int
extern
fun mul_int3_int3: (int3, int3) -<> int3

 (* ****** ****** *)

 local

 assume
int3_t0ype = (int, int, int)

 in (* in-of-local *)
//
implement
int3 (x, y, z) = @(x, y, z)
//
implement int3_1 (xyz) = xyz.1
//
implement
mul_int3_int3
(
@(a,b,c), @(d,e,f)
) =
(a*d + b*e, a*e + b*f, b*e + c*f)
//
end // end of [local]

 (* ****** ****** *)
//
implement
gnumber_int<int3> (n) = int3(n, 0, n)
//
implement gmul_val<int3> = mul_int3_int3
//
(* ****** ****** *)
//
fun
fib (n: intGte(0)): int =
int3_1(gpow_int_val<int3> (n, int3(1, 1, 0)))
//
(* ****** ****** *)

 implement
main0 () =
{
//
val N = 10
val () = println! ("fib(", N, ") = ", fib(N))
val N = 20
val () = println! ("fib(", N, ") = ", fib(N))
val N = 30
val () = println! ("fib(", N, ") = ", fib(N))
val N = 40
val () = println! ("fib(", N, ") = ", fib(N))
//
} (* end of [main0] *)

AutoHotkey [edit]

Search autohotkey.com: sequence

Iterative [edit]

Translation of: C

          Loop          ,          5          
MsgBox % fib( A_Index )
Return

 fib(n)
{
If (n < 2 )
Return n
i := last := this := 1
While (i <= n)
{
new := last + this
last := this
this := new
i++
}
Return this
}

Recursive and iterative [edit]

Source: AutoHotkey forum by Laszlo

          /*
Important note: the recursive version would be very slow
without a global or static array. The iterative version
handles also negative arguments properly.
*/

 FibR(n) { ; n-th Fibonacci number (n>=0, recursive with static array Fibo)
Static
Return n< 2 ? n : Fibo%n% ? Fibo%n% : Fibo%n% := FibR(n- 1 ) +FibR(n- 2 )
}

 Fib(n) { ; n-th Fibonacci number (n < 0 OK, iterative)
a := 0 , b := 1
Loop % abs (n) - 1
c := b, b += a, a := c
Return n= 0 ? 0 : n> 0 || n& 1 ? b : -b
}

AutoIt [edit]

Iterative [edit]

#AutoIt Version: 3.2.10.0
$n0 = 0
$n1 = 1
$n = 10
MsgBox ( 0 , "Iterative Fibonacci " , it_febo( $n0 , $n1 , $n ) )

Func it_febo( $n_0 , $n_1 , $N )
$first = $n_0
$second = $n_1
$next = $first + $second
$febo = 0
For $i = 1 To $N - 3
$first = $second
$second = $next
$next = $first + $second
Next
if $n == 0 Then
$febo = 0
ElseIf $n == 1 Then
$febo = $n_0
ElseIf $n == 2 Then
$febo = $n_1
Else
$febo = $next
EndIf
Return $febo
EndFunc

Recursive [edit]

#AutoIt Version: 3.2.10.0
$n0 = 0
$n1 = 1
$n = 10
MsgBox ( 0 , "Recursive Fibonacci " , rec_febo( $n0 , $n1 , $n ) )
Func rec_febo( $r_0 , $r_1 , $R )
if $R < 3 Then
if $R == 2 Then
Return $r_1
ElseIf $R == 1 Then
Return $r_0
ElseIf $R == 0 Then
Return 0
EndIf
Return $R
Else
Return rec_febo( $r_0 , $r_1 , $R - 1 ) + rec_febo( $r_0 , $r_1 , $R - 2 )
EndIf
EndFunc

AWK [edit]

As in many examples, this one-liner contains the function as well as testing with input from stdin, output to stdout.

$ awk 'func fib(n)          {          return          (n<          2          ?n:fib(n-          1          )          +fib(n-          2          )          )          }          {          print          "fib("          $1          ")="fib(          $1          )          }'
10
fib( 10 )=55

Axe [edit]

A recursive solution is not practical in Axe because there is no concept of variable scope in Axe.

Iterative solution:

Lbl FIB
r₁→N
0→I
1→J
For(K,1,N)
I+J→T
J→I
T→J
End
J
Return

Babel [edit]

In Babel, we can define fib using a stack-based approach that is not recursive:

fib { <- 0 1 { dup <- + -> swap } -> times zap } <

foo x < puts x in foo. In this case, x is the code list between the curly-braces. This is how you define callable code in Babel. The definition works by initializing the stack with 0, 1. On each iteration of the times loop, the function duplicates the top element. In the first iteration, this gives 0, 1, 1. Then it moves down the stack with the <- operator, giving 0, 1 again. It adds, giving 1. then it moves back up the stack, giving 1, 1. Then it swaps. On the next iteration this gives:

1, 1, 1 (dup)   1, 1, (<-)   2 (+)   2, 1 (->)   1, 2 (swap)        

And so on. To test fib:

{19 iter - fib !} 20 times collect ! lsnum !
( 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 )

bash [edit]

Iterative [edit]


$ fib=1;j=1;while ( (fib< 100 ) );do echo $fib;( ( k=fib+j,fib=j,j=k) );done
1 1 2 3 5 8 13 21 34 55 89        

Recursive [edit]

fib(          )          
{
if [ $1 -le 0 ]
then
echo 0
return 0
fi
if [ $1 -le 2 ]
then
echo 1
else
a=$(fib $[ $1-1 ] )
b=$(fib $[ $1-2 ] )
echo $( ( $a+$b ) )
fi
}

BASIC [edit]

Applesoft BASIC [edit]

Same code as Commodore BASIC

Entering a value of N > 183, produces an error message:

?OVERFLOW ERROR IN 40

BASIC256 [edit]


# Basic-256 ver 1.1.4
# iterative Fibonacci sequence
# Matches sequence A000045 in the OEIS, https://oeis.org/A000045/list

 # Return the Nth Fibonacci number

 input "N = ",f
limit = 500 # set upper limit - can be changed, removed
f = int(f)
if f > limit then f = limit
a = 0 : b = 1 : c = 0 : n = 0 # initial values

  while n < f
print n + chr(9) + c # chr(9) = tab
a = b
b = c
c = a + b
n += 1

 end while

 print " "
print n + chr(9) + c

Commodore BASIC [edit]

100 PRINT CHR$(147); CHR$(18); "****      FIBONACCI GENERATOR       ****"
110 INPUT "MIN, MAX"; N1, N2
120 IF N1 > N2 THEN T = N1: N1 = N2: N2 = T
130 A = 0: B = 1: S = SGN(N1)
140 FOR I = S TO N1 STEP S
150 : IF S > 0 THEN T = A + B: A = B: B = T
160 : IF S < 0 THEN T = B - A: B = A: A = T
170 NEXT I
180 PRINT
190 PRINT STR$(A); : REM STR$() PREVENTS TRAILING SPACE
200 IF N2 = N1 THEN 250
210 FOR I = N1 + 1 TO N2
220 : T = A + B: A = B: B = T
230 : PRINT ","; STR$(A);
240 NEXT I
250 PRINT
****      FIBONACCI GENERATOR       ****  MIN, MAX? -6,6  -8, 5,-3, 2,-1, 1, 0, 1, 1, 2, 3, 5, 8  READY.

Integer BASIC [edit]

Only works with quite small values of n {\displaystyle n} .

          10 INPUT N
20 A=0
30 B=1
40 FOR I=2 TO N
50 C=B
60 B=A+B
70 A=C
80 NEXT I
90 PRINT B
100 END

IS-BASIC [edit]

100 PROGRAM "Fibonac.bas"
110 FOR I=0 TO 20
120 PRINT "F";I,FIB(I)
130 NEXT
140 DEF FIB(N)
150 NUMERIC I
160 LET A=0:LET B=1
170 FOR I=1 TO N
180 LET T=A+B:LET A=B:LET B=T
190 NEXT
200 LET FIB=A
210 END DEF

QBasic [edit]

Iterative [edit]

          FUNCTION          itFib          (n)          
n1 = 0
n2 = 1
FOR k = 1 TO ABS (n)
sum = n1 + n2
n1 = n2
n2 = sum
NEXT k
IF n < 0 THEN
itFib = n1 * ( ( - 1 ) ^ ( ( -n) + 1 ) )
ELSE
itFib = n1
END IF
END FUNCTION

Next version calculates each value once, as needed, and stores the results in an array for later retreival (due to the use of REDIM PRESERVE, it requires QuickBASIC 4.5 or newer):

          DECLARE          FUNCTION          fibonacci&          (n          AS          INTEGER          )          

REDIM SHARED fibNum( 1 ) AS LONG

 fibNum( 1 ) = 1

'*****sample inputs*****
PRINT fibonacci( 0 ) 'no calculation needed
PRINT fibonacci( 13 ) 'figure F(2)..F(13)
PRINT fibonacci( - 42 ) 'figure F(14)..F(42)
PRINT fibonacci( 47 ) 'error: too big
'*****sample inputs*****

FUNCTION fibonacci& (n AS INTEGER )
DIM a AS INTEGER
a = ABS (n)
SELECT CASE a
CASE 0 TO 46
SHARED fibNum( ) AS LONG
DIM u AS INTEGER , L0 AS INTEGER
u = UBOUND (fibNum)
IF a > u THEN
REDIM PRESERVE fibNum(a) AS LONG
FOR L0 = u + 1 TO a
fibNum(L0) = fibNum(L0 - 1 ) + fibNum(L0 - 2 )
NEXT
END IF
IF n < 0 THEN
fibonacci = fibNum(a) * ( ( - 1 ) ^ (a + 1 ) )
ELSE
fibonacci = fibNum(n)
END IF
CASE ELSE
'limited to signed 32-bit int (LONG)
'F(47)=&hB11924E1
ERROR 6 'overflow
END SELECT
END FUNCTION

(unhandled error in final input prevents output):

          0  233 -267914296        

Recursive [edit]

This example can't handle n < 0.

          FUNCTION          recFib          (n)          
IF (n < 2 ) THEN
recFib = n
ELSE
recFib = recFib(n - 1 ) + recFib(n - 2 )
END IF
END FUNCTION

Array (Table) Lookup [edit]

This uses a pre-generated list, requiring much less run-time processor usage. (Since the sequence never changes, this is probably the best way to do this in "the real world". The same applies to other sequences like prime numbers, and numbers like pi and e.)

          DATA          -          1836311903          ,          1134903170          ,-          701408733          ,          433494437          ,-          267914296          ,          165580141          ,-          102334155          
DATA 63245986 ,- 39088169 , 24157817 ,- 14930352 , 9227465 ,- 5702887 , 3524578 ,- 2178309
DATA 1346269 ,- 832040 , 514229 ,- 317811 , 196418 ,- 121393 , 75025 ,- 46368 , 28657 ,- 17711
DATA 10946 ,- 6765 , 4181 ,- 2584 , 1597 ,- 987 , 610 ,- 377 , 233 ,- 144 , 89 ,- 55 , 34 ,- 21 , 13 ,- 8 , 5 ,- 3
DATA 2 ,- 1 , 1 , 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144 , 233 , 377 , 610 , 987 , 1597 , 2584 , 4181 , 6765
DATA 10946 , 17711 , 28657 , 46368 , 75025 , 121393 , 196418 , 317811 , 514229 , 832040 , 1346269
DATA 2178309 , 3524578 , 5702887 , 9227465 , 14930352 , 24157817 , 39088169 , 63245986
DATA 102334155 , 165580141 , 267914296 , 433494437 , 701408733 , 1134903170 , 1836311903

DIM fibNum( - 46 TO 46 ) AS LONG

FOR n = - 46 TO 46
READ fibNum(n)
NEXT

'*****sample inputs*****
FOR n = - 46 TO 46
PRINT fibNum(n) ,
NEXT
PRINT
'*****sample inputs*****

Fibonacci from Russia [edit]

Fibonacci from Russia

          'FibRus.bas          
DIM F( 80 ) AS DOUBLE
F( 1 ) = 0: F( 2 ) = 1
'OPEN "FibRus.txt" FOR OUTPUT AS #1
FOR i = 3 TO 80
F(i) = F(i- 1 ) +F(i- 2 )
NEXT i

FOR i = 1 TO 80
f$ = STR$ (F(i) ): LF = 22 - LEN (f$)
n$ = ""
FOR j = 1 TO LF: n$ = " " + n$: NEXT
f$ = n$ + f$
PRINT i, f$: ' PRINT #1, i, f$
NEXT i

1
0
2 1
3 1
4 2
5 3
6 5
7 8
8 13
9 21
...
24 28657
25 46368
26 75025
...
36 9227465
37 14930352
38 24157817
...
48 2971215073
49 4807526976
50 7778742049
...
60 956722026041
61 1548008755920
62 2504730781961
...
76 2111485077978050
77 3416454622906707
78 5527939700884757
79 8944394323791464
80 1.447233402467622D+ 16

Sinclair ZX81 BASIC [edit]

Analytic [edit]

          10 INPUT N
20 PRINT INT (0.5+(((SQR 5+1)/2)**N)/SQR 5)

Iterative [edit]

          10 INPUT N
20 LET A=0
30 LET B=1
40 FOR I=2 TO N
50 LET C=B
60 LET B=A+B
70 LET A=C
80 NEXT I
90 PRINT B

Tail recursive [edit]

          10 INPUT N
20 LET A=0
30 LET B=1
40 GOSUB 70
50 PRINT B
60 STOP
70 IF N=1 THEN RETURN
80 LET C=B
90 LET B=A+B
100 LET A=C
110 LET N=N-1
120 GOSUB 70
130 RETURN

Batch File [edit]

Recursive version

          ::fibo.cmd          
@ echo off
if "% 1" equ "" goto :eof
call :fib % 1
echo % errorlevel %
goto :eof

 :fib
setlocal enabledelayedexpansion
if % 1 geq 2 goto :ge2
exit /b % 1

 :ge2
set /a r1 = % 1 - 1
set /a r2 = % 1 - 2
call :fib ! r1 !
set r1=% errorlevel %
call :fib ! r2 !
set r2=% errorlevel %
set /a r0 = r1 + r2
exit /b ! r0 !

>for /L %i in (1,5,20) do fibo.cmd %i  >fibo.cmd 1 1  >fibo.cmd 6 8  >fibo.cmd 11 89  >fibo.cmd 16 987

Battlestar [edit]


// Fibonacci sequence, recursive version
fun fibb
loop
a = funparam[ 0 ]
break (a < 2 )

  a--

  // Save "a" while calling fibb
a -> stack

  // Set the parameter and call fibb
funparam[ 0 ] = a
call fibb

  // Handle the return value and restore "a"
b = funparam[ 0 ]
stack -> a

  // Save "b" while calling fibb again
b -> stack

  a--

  // Set the parameter and call fibb
funparam[ 0 ] = a
call fibb

  // Handle the return value and restore "b"
c = funparam[ 0 ]
stack -> b

  // Sum the results
b += c
a = b

  funparam[ 0 ] = a

  break
end
end

// vim: set syntax=c ts=4 sw=4 et:

BBC BASIC [edit]

          PRINT FNfibonacci_r(1),  FNfibonacci_i(1)
PRINT FNfibonacci_r(13), FNfibonacci_i(13)
PRINT FNfibonacci_r(26), FNfibonacci_i(26)
END

  DEF FNfibonacci_r(N)
IF N < 2 THEN = N
= FNfibonacci_r(N-1) + FNfibonacci_r(N-2)

  DEF FNfibonacci_i(N)
LOCAL F, I, P, T
IF N < 2 THEN = N
P = 1
FOR I = 1 TO N
T = F
F += P
P = T
NEXT
= F

          1         1        233       233     121393    121393

bc [edit]

iterative [edit]

#! /usr/bin/bc -q

 define fib(x) {
if (x <= 0) return 0;
if (x == 1) return 1;

  a = 0;
b = 1;
for (i = 1; i < x; i++) {
c = a+b; a = b; b = c;
}
return c;
}
fib(1000)
quit

BCPL [edit]

get "libhdr"

 let fib(n) = n<=1 -> n, valof
$( let a=0 and b=1
for i=2 to n
$( let c=a
a := b
b := a+c
$)
resultis b
$)

 let start() be
for i=0 to 10 do
writef("F_%N*T= %N*N", i, fib(i))

F_0     = 0 F_1     = 1 F_2     = 1 F_3     = 2 F_4     = 3 F_5     = 5 F_6     = 8 F_7     = 13 F_8     = 21 F_9     = 34 F_10    = 55

beeswax [edit]

          #>'#{;
_`Enter n: `TN`Fib(`{`)=`X~P~K#{;
#>~P~L#[email protected]>[email protected]'[email protected]{;
[email protected]<

Example output:

Notice the UInt64 wrap-around at Fib(94)!

julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i0

 Fib(0)=0
Program finished!

 julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i10

 Fib(10)=55
Program finished!

 julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i92

 Fib(92)=7540113804746346429
Program finished!

 julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i93

 Fib(93)=12200160415121876738
Program finished!

 julia> beeswax("n-th Fibonacci number.bswx")
Enter n: i94

 Fib(94)=1293530146158671551
Program finished!

Befunge [edit]

00:.1:.>:"@"8**++\1+:67+`#@_v
^ .:\/*8"@"\%*8"@":\ <

Bracmat [edit]

Recursive [edit]

fib=.!arg:<2|fib$(!arg+-2)+fib$(!arg+-1)
          fib$30  832040        

Iterative [edit]

(fib=
last i this new
.  !arg:<2
| 0:?last:?i
& 1:?this
& whl
' ( !i+1:<!arg:?i
& !last+!this:?new
& !this:?last
& !new:?this
)
& !this
)
          fib$777  1081213530912648191985419587942084110095342850438593857649766278346130479286685742885693301250359913460718567974798268702550329302771992851392180275594318434818082        

Brainf*** [edit]

Works with: Brainf*** version implementations with unbounded cell size

The first cell contains n (10), the second cell will contain fib(n) (55), and the third cell will contain fib(n-1) (34).

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

The following generates n fibonacci numbers and prints them, though not in ascii. It does have a limit due to the cells usually being 1 byte in size.

          +++++          +++++                      #0 set to n          
>> + Init #2 to 1
<<
[
- #Decrement counter in #0
>> . Notice: This doesn't print it in ascii
To look at results you can pipe into a file and look with a hex editor

Copying sequence to save #2 in #4 using #5 as restore space
>> [ - ] Move to #4 and clear
> [ - ] Clear #5
<<< #2
[ Move loop
- >> + > + <<< Subtract #2 and add #4 and #5
]
>>>
[ Restore loop
- <<< + >>> Subtract from #5 and add to #2
]

  <<<< Back to #1
Non destructive add sequence using #3 as restore value
[ Loop to add
- > + > + << Subtract #1 and add to value #2 and restore space #3
]
>>
[ Loop to restore #1 from #3
- << + >> Subtract from restore space #3 and add in #1
]

  << [ - ] Clear #1
>>>
[ Loop to move #4 to #1
- <<< + >>> Subtract from #4 and add to #1
]
<<<< Back to #0
]

Brat [edit]

Recursive [edit]

fibonacci = { x |
true? x < 2, x, { fibonacci(x - 1) + fibonacci(x - 2) }
}

Tail Recursive [edit]

fib_aux = { x, next, result |
true? x == 0,
result,
{ fib_aux x - 1, next + result, next }
}

 fibonacci = { x |
fib_aux x, 1, 0
}

Memoization [edit]

cache = hash.new

 fibonacci = { x |
true? cache.key?(x)
{ cache[x] }
{true? x < 2, x, { cache[x] = fibonacci(x - 1) + fibonacci(x - 2) }}
}

Burlesque [edit]


{0 1}{^^++[+[-^^-]\/}30.*\[e!vv

0 1{{.+}c!}{1000.<}w!

C [edit]

Recursive [edit]

          long          long          fibb(          long          long          a,          long          long          b,          int          n)          {          
return ( --n> 0 ) ? (fibb(b, a+b, n) ) : (a) ;
}

Iterative [edit]

          long          long          int          fibb(          int          n)          {          
int fnow = 0 , fnext = 1 , tempf;
while ( --n> 0 ) {
tempf = fnow + fnext;
fnow = fnext;
fnext = tempf;
}
return fnext;
}

Analytic [edit]

          #include <tgmath.h>          
#define PHI ((1 + sqrt(5))/2)

long long unsigned fib( unsigned n) {
return floor ( ( pow (PHI, n) - pow ( 1 - PHI, n) ) / sqrt ( 5 ) ) ;
}

Generative [edit]

Translation of: Python

Works with: gcc version version 4.1.2 20080704 (Red Hat 4.1.2-44)

          #include <stdio.h>          
typedef enum { false = 0 , true =! 0 } bool;
typedef void iterator;

#include <setjmp.h>
/* declare label otherwise it is not visible in sub-scope */
#define LABEL(label) jmp_buf label; if(setjmp(label))goto label;
#define GOTO(label) longjmp(label, true)

/* the following line is the only time I have ever required "auto" */
#define FOR(i, iterator) { auto bool lambda(i); yield_init = (void *)&lambda; iterator; bool lambda(i)
#define DO {
#define YIELD(x) if(!yield(x))return
#define BREAK return false
#define CONTINUE return true
#define OD CONTINUE; } }

static volatile void *yield_init; /* not thread safe */
#define YIELDS(type) bool (*yield)(type) = yield_init

 iterator fibonacci( int stop) {
YIELDS( int ) ;
int f[ ] = { 0 , 1 } ;
int i;
for (i= 0 ; i<stop; i++ ) {
YIELD(f[i% 2 ] ) ;
f[i% 2 ] =f[ 0 ] +f[ 1 ] ;
}
}

 main( ) {
printf ( "fibonacci: " ) ;
FOR( int i, fibonacci( 16 ) ) DO
printf ( "%d, " ,i) ;
OD;
printf ( "...\n" ) ;
}

fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, ...        

Fast method for a single large value [edit]

          #include <stdlib.h>          
#include <stdio.h>
#include <gmp.h>

typedef struct node node;
struct node {
int n;
mpz_t v;
node *next;
} ;

#define CSIZE 37
node *cache[CSIZE] ;

// very primitive linked hash table
node * find_cache( int n)
{
int idx = n % CSIZE;
node *p;

  for (p = cache[idx] ; p && p->n != n; p = p->next) ;
if (p) return p;

  p = malloc ( sizeof (node) ) ;
p->next = cache[idx] ;
cache[idx] = p;

  if (n < 2 ) {
p->n = n;
mpz_init_set_ui(p->v, 1 ) ;
} else {
p->n = - 1 ; // -1: value not computed yet
mpz_init(p->v) ;
}
return p;
}

 mpz_t tmp1, tmp2;
mpz_t *fib( int n)
{
int x;
node *p = find_cache(n) ;

  if (p->n < 0 ) {
p->n = n;
x = n / 2 ;

  mpz_mul(tmp1, *fib(x- 1 ) , *fib(n - x - 1 ) ) ;
mpz_mul(tmp2, *fib(x) , *fib(n - x) ) ;
mpz_add(p->v, tmp1, tmp2) ;
}
return &p->v;
}

int main( int argc, char **argv)
{
int i, n;
if (argc < 2 ) return 1 ;

  mpz_init(tmp1) ;
mpz_init(tmp2) ;

  for (i = 1 ; i < argc; i++ ) {
n = atoi (argv[i] ) ;
if (n < 0 ) {
printf ( "bad input: %s\n" , argv[i] ) ;
continue ;
}

  // about 75% of time is spent in printing
gmp_printf( "%Zd\n" , *fib(n) ) ;
}
return 0 ;
}

% ./a.out 0 1 2 3 4 5 1 1 2 3 5 8 % ./a.out 10000000 | wc -c    # count length of output, including the newline 1919488        

C# [edit]

Recursive [edit]


public static ulong Fib( uint n) {
return (n < 2 ) ? n : Fib(n - 1 ) + Fib(n - 2 ) ;
}

Tail-Recursive [edit]


public static ulong Fib( uint n) {
return Fib( 0, 1, n) ;
}

private static ulong Fib( ulong a, ulong b, uint n) {
return (n < 1 ) ? a : (n == 1 ) ? b : Fib(b, a + b, n - 1 ) ;
}

Iterative [edit]


public static ulong Fib( uint x) {
if (x == 0 ) return 0 ;

  ulong prev = 0 ;
ulong next = 1 ;
for ( int i = 1 ; i < x; i++ )
{
ulong sum = prev + next;
prev = next;
next = sum;
}
return next;
}

Eager-Generative [edit]


public static IEnumerable< long > Fibs( uint x) {
IList< ulong > fibs = new List< ulong > ( ) ;

  ulong prev = - 1 ;
ulong next = 1 ;
for ( int i = 0 ; i < x; i++ )
{
long sum = prev + next;
prev = next;
next = sum;
fibs. Add (sum) ;
}
return fibs;
}

Lazy-Generative [edit]


public static IEnumerable< ulong > Fibs( uint x) {
ulong prev = - 1 ;
ulong next = 1 ;
for ( uint i = 0 ; i < x; i++ ) {
ulong sum = prev + next;
prev = next;
next = sum;
yield return sum;
}
}

Analytic [edit]

This returns digits up to the 93rd Fibonacci number, but the digits become inaccurate past the 71st. There is custom rounding applied to the result that allows the function to be accurate at the 71st number instead of topping out at the 70th.

          static          double          r5          =          Math.          Sqrt          (          5.0          ), Phi          =          (r5          +          1.0          )          /          2.0          ;          

static ulong fib( uint n) {
If (n > 71 ) throw new ArgumentOutOfRangeException( "n", n, "Needs to be smaller than 72." ) ;
double r = Math. Pow (Phi, n) / r5;
return ( ulong ) (n < 64 ? Math. Round (r) : Math. Floor (r) ) ; }

To get to the 93rd Fibonacci number, one must use the decimal type, rather than the double type, like this:

          static          decimal          Sqrt_dec(          decimal          x,          decimal          g)          {          decimal          t, lg;          
do { t = x / g; lg = g; g = (t + g) / 2M; } while (lg != g) ;
return g; }

static decimal Pow_dec ( decimal bas, uint exp) {
if (exp == 0 ) return 1M;
decimal tmp = Pow_dec(bas, exp >> 1 ) ; tmp *= tmp;
if ( (exp & 1 ) == 1 ) tmp *= bas; return tmp; }

static decimal r5 = Sqrt_dec(5.0M, ( decimal )Math. Sqrt ( 5.0 ) ),
Phi = (r5 + 1.0M) / 2.0M;

static ulong fib( uint n) {
If (n > 93 ) throw new ArgumentOutOfRangeException( "n", n, "Needs to be smaller than 94." ) ;
decimal r = Pow_dec(Phi, n) / r5;
return ( ulong ) (n < 64 ? Math. Round (r) : Math. Floor (r) ) ; }

Note that the Math.Pow() function and the Math.Sqrt() function must be replaced with ones returning the decimal type.

If one allows the fib() function to return the decimal type, one can reach the 138th Fibonacci number. However, the accuracy is lost after the 128th.

          static          decimal          Sqrt_dec(          decimal          x,          decimal          g)          {          decimal          t, lg;          
do { t = x / g; lg = g; g = (t + g) / 2M; } while (lg != g) ;
return g; }

static decimal Pow_dec ( decimal bas, uint exp) {
if (exp == 0 ) return 1M;
decimal tmp = Pow_dec(bas, exp >> 1 ) ; tmp *= tmp;
if ( (exp & 1 ) == 1 ) tmp *= bas; return tmp; }

static decimal r5 = Sqrt_dec(5.0M, ( decimal )Math. Sqrt ( 5.0 ) ),
Phi = (r5 + 1.0M) / 2.0M;

static decimal fib( uint n) {
If (n > 128 ) throw new ArgumentOutOfRangeException( "n", n, "Needs to be smaller than 129." ) ;
decimal r = Pow_dec(Phi, n) / r5;
return n < 64 ? Math. Round (r) : Math. Floor (r) ; }

Matrix [edit]

Algorithm is based on

( 1 1 1 0 ) n = ( F ( n + 1 ) F ( n ) F ( n ) F ( n 1 ) ) {\displaystyle {\begin{pmatrix}1&1\\1&0\end{pmatrix}}^{n}={\begin{pmatrix}F(n+1)&F(n)\\F(n)&F(n-1)\end{pmatrix}}} .

Needs System.Windows.Media.Matrix or similar Matrix class. Calculates in O ( n ) {\displaystyle O(n)} .


public static ulong Fib( uint n) {
var M = new Matrix( 1,0,0,1 ) ;
var N = new Matrix( 1,1,1,0 ) ;
for ( uint i = 1 ; i < n; i++ ) M *= N;
return ( ulong )M[ 0 ] [ 0 ] ;
}

Needs System.Windows.Media.Matrix or similar Matrix class. Calculates in O ( log n ) {\displaystyle O(\log {n})} .


private static Matrix M;
private static readonly Matrix N = new Matrix( 1,1,1,0 ) ;

public static ulong Fib( uint n) {
M = new Matrix( 1,0,0,1 ) ;
MatrixPow(n- 1 ) ;
return ( ulong )M[ 0 ] [ 0 ] ;
}

private static void MatrixPow( double n) {
if (n > 1 ) {
MatrixPow(n/ 2 ) ;
M *= M;
}
if (n % 2 == 0 ) M *= N;
}

Array (Table) Lookup [edit]


private static int [ ] fibs = new int [ ] { - 1836311903, 1134903170,
- 701408733, 433494437, - 267914296, 165580141, - 102334155,
63245986, - 39088169, 24157817, - 14930352, 9227465, - 5702887,
3524578, - 2178309, 1346269, - 832040, 514229, - 317811, 196418,
- 121393, 75025, - 46368, 28657, - 17711, 10946, - 6765, 4181,
- 2584, 1597, - 987, 610, - 377, 233, - 144, 89, - 55, 34, - 21, 13,
- 8, 5, - 3, 2, - 1, 1, 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 } ;

public static int Fib( int n) {
if (n < - 46 || n > 46 ) throw new ArgumentOutOfRangeException( "n", n, "Has to be between -46 and 47." )
return fibs[n+ 46 ] ;
}

Arbitrary Precision [edit]

This large step recurrence routine can calculate the two millionth Fibonacci number in under 1 / 5 second at tio.run. This routine can generate the fifty millionth Fibonacci number in under 30 seconds at tio.run. The unused conventional iterative method times out at two million on tio.run, you can only go to around 1,290,000 or so to keep the calculation time (plus string conversion time) under the 60 second timeout limit there. When using this large step recurrence method, it takes around 5 seconds to convert the two millionth Fibonacci number (417975 digits) into a string (so that one may count those digits).

          using          System          ;          
using System.Collections.Generic ;
using BI = System . Numerics . BigInteger ;

class Program
{
// A sparse array of values calculated along the way
static SortedList< int, BI> sl = new SortedList< int, BI> ( ) ;

  // This routine is semi-recursive, but doesn't need to evaluate every number up to n.
// Algorithm from here: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html#section3
static BI Fsl( int n)
{
if (n < 2 ) return n;
int n2 = n >> 1, pm = n2 + ( (n & 1 ) << 1 ) - 1 ; IfNec(n2) ; IfNec(pm) ;
return n2 > pm ? ( 2 * sl[pm] + sl[n2] ) * sl[n2] : sqr(sl[n2] ) + sqr(sl[pm] ) ;
// Helper routine for Fsl(). It adds an entry to the sorted list when necessary
void IfNec( int x) { if ( !sl. ContainsKey (x) ) sl. Add (x, Fsl(x) ) ; }
// Helper function to square a BigInteger
BI sqr(BI x) { return x * x; }
}

  // Conventional iteration method (not used here)
public static BI Fm(BI n)
{
if (n < 2 ) return n; BI cur = 0, pre = 1 ;
for ( int i = 0 ; i <= n - 1 ; i++ ) { BI sum = cur + pre; pre = cur; cur = sum; }
return cur;
}

  public static void Main( )
{
int num = 2_000_000, digs = 35, vlen;
var sw = System.Diagnostics . Stopwatch . StartNew ( ) ; var v = Fsl(num) ; sw. Stop ( ) ;
Console. Write ( "{0:n3} ms to calculate the {1:n0}th Fibonacci number, ",
sw. Elapsed . TotalMilliseconds, num) ;
Console. WriteLine ( "number of digits is {0}", vlen = ( int )Math. Ceiling (BI. Log10 (v) ) ) ;
if (vlen < 10000 ) {
sw. Restart ( ) ; Console. WriteLine (v) ; sw. Stop ( ) ;
Console. WriteLine ( "{0:n3} ms to write it to the console.", sw. Elapsed . TotalMilliseconds ) ;
} else
Console. Write ( "partial: {0}...{1}", v / BI. Pow ( 10, vlen - digs), v % BI. Pow ( 10, digs) ) ;
}
}

137.209 ms to calculate the 2,000,000th Fibonacci number, number of digits is 417975 partial: 85312949175076415430516606545038251...91799493108960825129188777803453125        

C++ [edit]

Using unsigned int, this version only works up to 48 before fib overflows.

          #include <iostream>          

int main( )
{
unsigned int a = 1, b = 1 ;
unsigned int target = 48 ;
for ( unsigned int n = 3 ; n <= target; ++n)
{
unsigned int fib = a + b;
std:: cout << "F(" << n << ") = " << fib << std:: endl ;
a = b;
b = fib;
}

  return 0 ;
}

This version does not have an upper bound.

          #include <iostream>          
#include <gmpxx.h>

int main( )
{
mpz_class a = mpz_class( 1 ), b = mpz_class( 1 ) ;
mpz_class target = mpz_class( 100 ) ;
for (mpz_class n = mpz_class( 3 ) ; n <= target; ++n)
{
mpz_class fib = b + a;
if ( fib < b )
{
std:: cout << "Overflow at " << n << std:: endl ;
break ;
}
std:: cout << "F(" << n << ") = " << fib << std:: endl ;
a = b;
b = fib;
}
return 0 ;
}

Version using transform:

          #include <algorithm>          
#include <vector>
#include <functional>
#include <iostream>

unsigned int fibonacci( unsigned int n) {
if (n == 0 ) return 0 ;
std:: vector < int > v(n+ 1 ) ;
v[ 1 ] = 1 ;
transform(v.begin ( ), v.end ( ) - 2, v.begin ( ) + 1, v.begin ( ) + 2, std:: plus < int > ( ) ) ;
// "v" now contains the Fibonacci sequence from 0 up
return v[n] ;
}

Far-fetched version using adjacent_difference:

          #include <numeric>          
#include <vector>
#include <functional>
#include <iostream>

unsigned int fibonacci( unsigned int n) {
if (n == 0 ) return 0 ;
std:: vector < int > v(n, 1 ) ;
adjacent_difference(v.begin ( ), v.end ( ) - 1, v.begin ( ) + 1, std:: plus < int > ( ) ) ;
// "array" now contains the Fibonacci sequence from 1 up
return v[n- 1 ] ;
}

Version which computes at compile time with metaprogramming:

          #include <iostream>          

template < int n> struct fibo
{
enum {value=fibo<n- 1 > :: value +fibo<n- 2 > :: value } ;
} ;

template <> struct fibo< 0 >
{
enum {value= 0 } ;
} ;

template <> struct fibo< 1 >
{
enum {value= 1 } ;
} ;

 int main( int argc, char const *argv[ ] )
{
std:: cout <<fibo< 12 > :: value <<std:: endl ;
std:: cout <<fibo< 46 > :: value <<std:: endl ;
return 0 ;
}

The following version is based on fast exponentiation:

          #include <iostream>          

inline void fibmul( int * f, int * g)
{
int tmp = f[ 0 ] *g[ 0 ] + f[ 1 ] *g[ 1 ] ;
f[ 1 ] = f[ 0 ] *g[ 1 ] + f[ 1 ] * (g[ 0 ] + g[ 1 ] ) ;
f[ 0 ] = tmp;
}

int fibonacci( int n)
{
int f[ ] = { 1, 0 } ;
int g[ ] = { 0, 1 } ;
while (n > 0 )
{
if (n & 1 ) // n odd
{
fibmul(f, g) ;
--n;
}
else
{
fibmul(g, g) ;
n >>= 1 ;
}
}
return f[ 1 ] ;
}

int main( )
{
for ( int i = 0 ; i < 20 ; ++i)
std:: cout << fibonacci(i) << " " ;
std:: cout << std:: endl ;
}

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181        

Using Zeckendorf Numbers [edit]

The nth fibonacci is represented as Zeckendorf 1 followed by n-1 zeroes. Here I define a class N which defines the operations increment ++() and comparison <=(other N) for Zeckendorf Numbers.


// Use Zeckendorf numbers to display Fibonacci sequence.
// Nigel Galloway October 23rd., 2012
int main( void ) {
char NG[ 22 ] = { '1',0 } ;
int x = - 1 ;
N G;
for ( int fibs = 1 ; fibs <= 20 ; fibs++ ) {
for ( ;G <= N(NG) ; ++G) x++ ;
NG[fibs] = '0' ;
NG[fibs+ 1 ] = 0 ;
std:: cout << x << " " ;
}
std:: cout << std:: endl ;
return 0 ;
}
1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946        

Using Standard Template Library [edit]

Possibly less "Far-fetched version".


// Use Standard Template Library to display Fibonacci sequence.
// Nigel Galloway March 30th., 2013
#include <algorithm>
#include <iostream>
#include <iterator>
int main( )
{
int x = 1, y = 1 ;
generate_n(std:: ostream_iterator < int > (std:: cout, " " ), 21, [ & ] { int n=x; x=y; y+ =n; return n; } ) ;
return 0 ;
}

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946

Cat [edit]

define fib {
dup 1 <=
[]
[dup 1 - fib swap 2 - fib +]
if
}

Chapel [edit]

iter fib() {
var a = 0, b = 1;

  while true {
yield a;
(a, b) = (b, b + a);
}
}

Chef [edit]

Stir-Fried Fibonacci Sequence.

 An unobfuscated iterative implementation.
It prints the first N + 1 Fibonacci numbers,
where N is taken from standard input.

 Ingredients.
0 g last
1 g this
0 g new
0 g input

 Method.
Take input from refrigerator.
Put this into 4th mixing bowl.
Loop the input.
Clean the 3rd mixing bowl.
Put last into 3rd mixing bowl.
Add this into 3rd mixing bowl.
Fold new into 3rd mixing bowl.
Clean the 1st mixing bowl.
Put this into 1st mixing bowl.
Fold last into 1st mixing bowl.
Clean the 2nd mixing bowl.
Put new into 2nd mixing bowl.
Fold this into 2nd mixing bowl.
Put new into 4th mixing bowl.
Endloop input until looped.
Pour contents of the 4th mixing bowl into baking dish.

 Serves 1.

Clio [edit]

Clio is pure and functions are lazy and memoized by default

fn fib n:
if n < 2: n
else: (n - 1 -> fib) + (n - 2 -> fib)

 [0:100] -> * fib -> * print

Clojure [edit]

Lazy Sequence [edit]

This is implemented idiomatically as an infinitely long, lazy sequence of all Fibonacci numbers:

          (          defn          fibs          [          ]          
( map first ( iterate ( fn [ [a b] ] [b ( + a b) ] ) [ 0 1 ] ) ) )

Thus to get the nth one:

          (nth          (fibs)          5          )        

So long as one does not hold onto the head of the sequence, this is unconstrained by length.

The one-line implementation may look confusing at first, but on pulling it apart it actually solves the problem more "directly" than a more explicit looping construct.

          (          defn          fibs          [          ]          
( map first ;; throw away the "metadata" (see below) to view just the fib numbers
( iterate ;; create an infinite sequence of [prev, curr] pairs
( fn [ [a b] ] ;; to produce the next pair, call this function on the current pair
[b ( + a b) ] ) ;; new prev is old curr, new curr is sum of both previous numbers
[ 0 1 ] ) ) ) ;; recursive base case: prev 0, curr 1

A more elegant solution is inspired by the Haskell implementation of an infinite list of Fibonacci numbers:

          (          def          fib          (          lazy-cat          [          0          1          ]          (          map          +          fib          (          rest          fib)          )          )          )        

Then, to see the first ten,

user>          (          take          10          fib)          
( 0 1 1 2 3 5 8 13 21 34 )

Iterative [edit]

Here's a simple interative process (using a recursive function) that carries state along with it (as args) until it reaches a solution:

          ;; max is which fib number you'd like computed (0th, 1st, 2nd, etc.)          
;; n is which fib number you're on for this call (0th, 1st, 2nd, etc.)
;; j is the nth fib number (ex. when n = 5, j = 5)
;; i is the nth - 1 fib number
( defn- fib-iter
[max n i j]
( if ( = n max)
j
( recur max
( inc n)
j
( + i j) ) ) )

( defn fib
[max]
( if ( < max 2 )
max
(fib-iter max 1 0N 1N) ) )

"defn-" means that the function is private (for use only inside this library). The "N" suffixes on integers tell Clojure to use arbitrary precision ints for those.

Doubling Algorithm (Fast) [edit]

Based upon the doubling algorithm which computes in O(log (n)) time as described here https://www.nayuki.io/page/fast-fibonacci-algorithms Implementation credit: https://stackoverflow.com/questions/27466311/how-to-implement-this-fast-doubling-fibonacci-algorithm-in-clojure/27466408#27466408


( defn fib [n]
( letfn [ (fib* [n]
( if ( zero? n)
[ 0 1 ]
( let [ [a b] (fib* (quot n 2 ) )
c ( *' a ( -' ( *' 2 b) a) )
d ( +' ( *' b b) ( *' a a) ) ]
( if (even? n)
[c d]
[d ( +' c d) ] ) ) ) ) ]
( first (fib* n) ) ) )

Recursive [edit]

A naive slow recursive solution:

          (          defn          fib          [n]          
(case n
0 0
1 1
( + (fib ( - n 1 ) )
(fib ( - n 2 ) ) ) ) )

This can be improved to an O(n) solution, like the iterative solution, by memoizing the function so that numbers that have been computed are cached. Like a lazy sequence, this also has the advantage that subsequent calls to the function use previously cached results rather than recalculating.

          (          def          fib
(memoize
( fn [n]
(case n
0 0
1 1
( + (fib ( - n 1 ) )
(fib ( - n 2 ) ) ) ) ) ) )

Using core.async [edit]

          (          ns          fib.core)          
(require '[clojure.core.async
:refer [ <! >! >!! <!! timeout chan alt! go] ] )

( defn fib [c]
( loop [a 0 b 1 ]
( >!! c a)
( recur b ( + a b) ) ) )

 ( defn -main [ ]
( let [c (chan) ]
(go (fib c) )
( dorun
( for [i ( range 10 ) ]
(println ( <!! c) ) ) ) ) )

CLU [edit]

% Generate Fibonacci numbers
fib = iter () yields (int)
a: int := 0
b: int := 1

  while true do
yield (a)
a, b := b, a+b
end
end fib

 % Grab the n'th value from an iterator
nth = proc [T: type] (g: itertype () yields (T), n: int) returns (T)
for v: T in g() do
if n<=0 then return (v) end
n := n-1
end
end nth

 % Print a few values
start_up = proc ()
po: stream := stream$primary_output()

   % print values coming out of the fibonacci iterator
% (which are generated one after the other without delay)
count: int := 0
for f: int in fib() do
stream$putl(po, "F(" || int$unparse(count) || ") = " || int$unparse(f))
count := count + 1
if count = 15 then break end
end

   % print a few random fibonacci numbers
% (to do this it has to restart at the beginning for each
% number, making it O(N))
fibs: sequence[int] := sequence[int]$[20,30,50]
for n: int in sequence[int]$elements(fibs) do
stream$putl(po, "F(" || int$unparse(n) || ") = "
|| int$unparse(nth[int](fib, n)))
end
end start_up

F(0) = 0 F(1) = 1 F(2) = 1 F(3) = 2 F(4) = 3 F(5) = 5 F(6) = 8 F(7) = 13 F(8) = 21 F(9) = 34 F(10) = 55 F(11) = 89 F(12) = 144 F(13) = 233 F(14) = 377 F(20) = 6765 F(30) = 832040 F(50) = 12586269025

CMake [edit]

Iteration uses a while() loop. Memoization uses global properties.

          set_property          (          GLOBAL          PROPERTY          fibonacci_0 0)          
set_property ( GLOBAL PROPERTY fibonacci_1 1)
set_property ( GLOBAL PROPERTY fibonacci_next 2)

# var = nth number in Fibonacci sequence.
function (fibonacci var n)
# If the sequence is too short, compute more Fibonacci numbers.
get_property (next GLOBAL PROPERTY fibonacci_next)
if ( NOT next GREATER ${n} )
# a, b = last 2 Fibonacci numbers
math (EXPR i "${next} - 2" )
get_property (a GLOBAL PROPERTY fibonacci_${i} )
math (EXPR i "${next} - 1" )
get_property (b GLOBAL PROPERTY fibonacci_${i} )

  while ( NOT next GREATER ${n} )
math (EXPR i "${a} + ${b}" ) # i = next Fibonacci number
set_property ( GLOBAL PROPERTY fibonacci_${next} ${i} )
set (a ${b} )
set (b ${i} )
math (EXPR next "${next} + 1" )
endwhile ()
set_property ( GLOBAL PROPERTY fibonacci_next ${next} )
endif ()

  get_property (answer GLOBAL PROPERTY fibonacci_${n} )
set ( ${var} ${answer} PARENT_SCOPE )
endfunction (fibonacci)

          # Test program: print 0th to 9th and 25th to 30th Fibonacci numbers.          
set (s "" )
foreach (i RANGE 0 9)
fibonacci(f ${i} )
set (s "${s} ${f}" )
endforeach (i)
set (s "${s} ... " )
foreach (i RANGE 25 30)
fibonacci(f ${i} )
set (s "${s} ${f}" )
endforeach (i)
message ( ${s} )
          0 1 1 2 3 5 8 13 21 34 ... 75025 121393 196418 317811 514229 832040

COBOL [edit]

Iterative [edit]

          Program-ID          .          Fibonacci-Sequence          .          
Data Division .
Working-Storage Section .
01 FIBONACCI-PROCESSING.
05 FIBONACCI-NUMBER PIC 9 ( 36 ) VALUE 0 .
05 FIB-ONE PIC 9 ( 36 ) VALUE 0 .
05 FIB-TWO PIC 9 ( 36 ) VALUE 1 .
01 DESIRED-COUNT PIC 9 ( 4 ) .
01 FORMATTING.
05 INTERM-RESULT PIC Z( 35 ) 9 .
05 FORMATTED-RESULT PIC X( 36 ) .
05 FORMATTED-SPACE PIC x( 35 ) .
Procedure Division .
000-START-PROGRAM .
Display "What place of the Fibonacci Sequence would you like (<173)? " with no advancing .
Accept DESIRED-COUNT .
If DESIRED-COUNT is less than 1
Stop run .
If DESIRED-COUNT is less than 2
Move FIBONACCI-NUMBER to INTERM-RESULT
Move INTERM-RESULT to FORMATTED-RESULT
Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE ,FORMATTED-RESULT
Display FORMATTED-RESULT
Stop run .
Subtract 1 from DESIRED-COUNT .
Move FIBONACCI-NUMBER to INTERM-RESULT.
Move INTERM-RESULT to FORMATTED-RESULT.
Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE ,FORMATTED-RESULT.
Display FORMATTED-RESULT.
Perform 100-COMPUTE-FIBONACCI until DESIRED-COUNT = zero .
Stop run .
100-COMPUTE-FIBONACCI.
Compute FIBONACCI-NUMBER = FIB-ONE + FIB-TWO.
Move FIB-TWO to FIB-ONE.
Move FIBONACCI-NUMBER to FIB-TWO.
Subtract 1 from DESIRED-COUNT .
Move FIBONACCI-NUMBER to INTERM-RESULT.
Move INTERM-RESULT to FORMATTED-RESULT.
Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE ,FORMATTED-RESULT.
Display FORMATTED-RESULT.

Recursive [edit]

          >>SOURCE          FREE
IDENTIFICATION DIVISION .
PROGRAM-ID . fibonacci-main .

DATA DIVISION .
WORKING-STORAGE SECTION .
01 num PIC 9 ( 6 ) COMP .
01 fib-num PIC 9 ( 6 ) COMP .

PROCEDURE DIVISION .
ACCEPT num
CALL "fibonacci" USING CONTENT num RETURNING fib-num
DISPLAY fib-num
.
END PROGRAM fibonacci-main .

IDENTIFICATION DIVISION .
PROGRAM-ID . fibonacci RECURSIVE.

DATA DIVISION .
LOCAL-STORAGE SECTION .
01 1-before PIC 9 ( 6 ) COMP .
01 2-before PIC 9 ( 6 ) COMP .

LINKAGE SECTION .
01 num PIC 9 ( 6 ) COMP .

01 fib-num PIC 9 ( 6 ) COMP BASED.

PROCEDURE DIVISION USING num RETURNING fib-num.
ALLOCATE fib-num
EVALUATE num
WHEN 0
MOVE 0 TO fib-num
WHEN 1
MOVE 1 TO fib-num
WHEN OTHER
SUBTRACT 1 FROM num
CALL "fibonacci" USING CONTENT num RETURNING 1-before
SUBTRACT 1 FROM num
CALL "fibonacci" USING CONTENT num RETURNING 2-before
ADD 1-before TO 2-before GIVING fib-num
END-EVALUATE
.
END PROGRAM fibonacci.

CoffeeScript [edit]

Analytic [edit]

fib_ana =          (n)          ->          
sqrt = Math.sqrt
phi = ( ( 1 + sqrt( 5 ) ) / 2 )
Math.round ( (Math.pow (phi, n) /sqrt( 5 ) ) )

Iterative [edit]

fib_iter =          (n)          ->          
return n if n < 2
[prev, curr] = [ 0 , 1 ]
[prev, curr] = [curr, curr + prev] for i in [ 1..n ]
curr

Recursive [edit]

fib_rec =          (n)          ->          
if n < 2 then n else fib_rec(n- 1 ) + fib_rec(n- 2 )

Comefrom0x10 [edit]

Recursion is is not possible in Comefrom0x10.

Iterative [edit]

stop = 6
a = 1
i = 1 # start
a # print result

 fib
comefrom if i is 1 # start
b = 1
comefrom fib # start of loop
i = i + 1
next_b = a + b
a = b
b = next_b

  comefrom fib if i > stop

Common Lisp [edit]

Note that Common Lisp uses bignums, so this will never overflow.

Iterative [edit]

          (          defun          fibonacci-iterative          (n          &aux          (f0          0          )          (f1          1          )          )          
( case n
( 0 f0)
( 1 f1)
(t (loop for n from 2 to n
for a = f0 then b and b = f1 then result
for result = (+ a b)
finally ( return result) ) ) ) )

Simpler one:

          (          defun          fibonacci          (n)          
( let ( (a 0 ) (b 1 ) (c n) )
(loop for i from 2 to n do
( setq c (+ a b)
a b
b c) )
c) )

Not a function, just printing out the entire (for some definition of "entire") sequence with a for var = loop:

          (loop for x          =          0          then y          and          y          =          1          then          (+ x y)          do          (          print          x)          )        

Recursive [edit]

          (          defun          fibonacci-recursive          (n)          
( if ( < n 2 )
n
(+ (fibonacci-recursive (- n 2 ) ) (fibonacci-recursive (- n 1 ) ) ) ) )
          (          defun          fibonacci-tail-recursive          (          n          &optional          (a          0          )          (b          1          )          )          
( if ( = n 0 )
a
(fibonacci-tail-recursive (- n 1 ) b (+ a b) ) ) )

Tail recursive and squaring:

          (          defun          fib          (n          &optional          (a          1          )          (b          0          )          (p          0          )          (q          1          )          )          
( if ( = n 1 ) (+ (* b p) (* a q) )
(fib (ash n -1 )
( if ( evenp n) a (+ (* b q) (* a (+ p q) ) ) )
( if ( evenp n) b (+ (* b p) (* a q) ) )
(+ (* p p) (* q q) )
(+ (* q q) (* 2 p q) ) ) ) ) ;p is Fib(2^n-1), q is Fib(2^n).

( print (fib 100000 ) )

Alternate solution [edit]

I use Allegro CL 10.1


;; Project : Fibonacci sequence

( defun fibonacci (nr)
( cond ( ( = nr 0 ) 1 )
( ( = nr 1 ) 1 )
(t (+ (fibonacci (- nr 1 ) )
(fibonacci (- nr 2 ) ) ) ) ) )
(format t "~a" "First 10 Fibonacci numbers" )
( dotimes (n 10 )
( if ( < n 1 ) (terpri) )
( if ( < n 9 ) (format t "~a" " " ) )
( write (+ n 1 ) ) (format t "~a" ": " )
( write (fibonacci n) ) (terpri) )

Output:

First 10 Fibonacci numbers  1: 1  2: 1  3: 2  4: 3  5: 5  6: 8  7: 13  8: 21  9: 34 10: 55        

Solution with methods and eql specializers [edit]


(defmethod fib (n)
(declare ( ( integer 0 *) n) )
(+ (fib (- n 1 ) )
(fib (- n 2 ) ) ) )

(defmethod fib ( (n ( eql 0 ) ) ) 0 )

(defmethod fib ( (n ( eql 1 ) ) ) 1 )

List-based iterative [edit]

This solution uses a list to keep track of the Fibonacci sequence for 0 or a positive integer.

          (          defun          fibo          (n)          
( cond ( ( < n 0 ) nil )
( ( < n 2 ) n)
(t ( let ( (leo '( 1 0 ) ) )
(loop for i from 2 upto n do
( setf leo ( cons (+ (first leo)
(second leo) )
leo) )
finally ( return (first leo) ) ) ) ) ) )
> (fibo 0) 0 > (fibo 1) 1 > (fibo 10) 55 > (fibo 100) 354224848179261915075 > (fibo 1000) 43466557686937456435688527675040625802564660517371780402481729089536555417949051890403879840079255169295922593080322634775209689623239873322471161642996440906533187938298969649928516003704476137795166849228875 > (fibo -10) NIL

List-based recursive [edit]

This solution computes Fibonacci numbers as either:

  1. a list starting from the first element;
  2. a single number;
  3. an interval from i-th to j-th element.


Options #2 and #3 can take negative parameters, but i (lowest index in range) must be greater than j (highest index in range).

Values are represented internally by a reversed list that grows from the head (and that's why we reverse it back when we return it).

          (defparameter *fibo-start* '(          1          1          )          )          ; elements 1 and 2          

;;; Helper functions
( defun grow-fibo (fibo)
( cons (+ (first fibo) (second fibo) ) fibo) )

( defun generate-fibo (fibo n) ; n must be > 1
( if ( equal (list-length fibo) n)
fibo
(generate-fibo (grow-fibo fibo) n) ) )

;;; User functions
( defun fibo (n)
( cond ( ( = n 0 ) 0 )
( ( = ( abs n) 1 ) 1 )
(t ( let ( (result (first (generate-fibo *fibo-start* ( abs n) ) ) ) )
( if ( and ( < n -1 ) ( evenp n) )
(- result)
result) ) ) ) )

( defun fibo-list (n)
( cond ( ( < n 1 ) nil )
( ( = n 1 ) '( 1 ) )
(t ( reverse (generate-fibo *fibo-start* n) ) ) ) )

( defun fibo-range (lower upper)
( if ( <= upper lower)
nil
( reverse (generate-fibo
( list
(fibo ( 1+ lower) )
(fibo lower) )
( 1+ (- upper lower) ) ) ) ) )

> (fibo 100) 354224848179261915075 > (fibo -150) -9969216677189303386214405760200 > (fibo-list 20) (1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765) > (fibo-range -10 15) (-55 34 -21 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610) > (fibo-range 0 20) (0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765)

Computer/zero Assembly [edit]

To find the n {\displaystyle n} th Fibonacci number, set the initial value of count equal to n {\displaystyle n} –2 and run the program. The machine will halt with the answer stored in the accumulator. Since Computer/zero's word length is only eight bits, the program will not work with values of n {\displaystyle n} greater than 13.

loop:   LDA  y      ; higher No.
STA temp
ADD x  ; lower No.
STA y
LDA temp
STA x

  LDA count
SUB one
BRZ done

  STA count
JMP loop

 done: LDA y
STP

 one: 1
count: 8  ; n = 10
x: 1
y: 1
temp: 0

Corescript [edit]

print Fibonacci Sequence:
var previous = 1
var number = 0
var temp = (blank)

 :fib
if number > 50000000000:kill
print (number)
set temp = (add number previous)
set previous = (number)
set number = (temp)
goto fib

 :kill
stop

Cowgol [edit]

include "cowgol.coh";

 sub fibonacci(n: uint32): (a: uint32) is
a := 0;
var b: uint32 := 1;
while n > 0 loop
var c := a + b;
a := b;
b := c;
n := n - 1;
end loop;
end sub;

 # test
var i: uint32 := 0;
while i < 20 loop
print_i32(fibonacci(i));
print_char(' ');
i := i + 1;
end loop;
print_nl();

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181

Crystal [edit]

Recursive [edit]

          def          fib(n)          
n < 2 ? n : fib(n - 1 ) + fib(n - 2 )
end

Iterative [edit]

          def          fibIterative(n, prevFib =          0, fib =          1          )          
return n if n < 2

  n.times do
prevFib, fib = fib, prevFib + fib
end

  prevFib
end

Tail Recursive [edit]

          def          fibTailRecursive(n, prevFib =          0, fib =          1          )          
n == 0 ? prevFib : fibTailRecursive(n - 1, fib, prevFib + fib)
end

Analytic [edit]

          def          fibBinet(n)          
( ( ( 5 ** 0.5 + 1 ) / 2 ) ** n / 5 ** 0.5 ).round.to_i
end

D [edit]

Here are four versions of Fibonacci Number calculating functions. FibD has an argument limit of magnitude 84 due to floating point precision, the others have a limit of 92 due to overflow (long).The traditional recursive version is inefficient. It is optimized by supplying a static storage to store intermediate results. A Fibonacci Number generating function is added. All functions have support for negative arguments.

          import          std.stdio          ,          std.conv          ,          std.algorithm          ,          std.math          ;          

long sgn( alias unsignedFib) ( int n) { // break sign manipulation apart
immutable uint m = (n >= 0 ) ? n : -n;
if (n < 0 && (n % 2 == 0 ) )
return -unsignedFib(m) ;
else
return unsignedFib(m) ;
}

long fibD( uint m) { // Direct Calculation, correct for abs(m) <= 84
enum sqrt5r = 1.0L / sqrt(5.0L) ; // 1 / sqrt(5)
enum golden = (1.0L + sqrt(5.0L) ) / 2.0L; // (1 + sqrt(5)) / 2
return roundTo! long (pow(golden, m) * sqrt5r) ;
}

long fibI( in uint m) pure nothrow { // Iterative
long thisFib = 0 ;
long nextFib = 1 ;
foreach (i; 0 .. m ) {
long tmp = nextFib;
nextFib += thisFib;
thisFib = tmp;
}
return thisFib;
}

long fibR( uint m) { // Recursive
return (m < 2 ) ? m : fibR(m - 1 ) + fibR(m - 2 ) ;
}

long fibM( uint m) { // memoized Recursive
static long [ ] fib = [ 0 , 1 ] ;
while (m >= fib.length )
fib ~= fibM(m - 2 ) + fibM(m - 1 ) ;
return fib[m] ;
}

alias sgn!fibD sfibD;
alias sgn!fibI sfibI;
alias sgn!fibR sfibR;
alias sgn!fibM sfibM;

auto fibG( in int m) { // generator(?)
immutable int sign = (m < 0 ) ? - 1 : 1 ;
long yield;

  return new class {
final int opApply( int delegate ( ref int , ref long ) dg) {
int idx = -sign; // prepare for pre-increment
foreach (f; this )
if (dg(idx += sign, f) )
break ;
return 0 ;
}

  final int opApply( int delegate ( ref long ) dg) {
long f0, f1 = 1 ;
foreach (p; 0 .. m * sign + 1 ) {
if (sign == - 1 && (p % 2 == 0 ) )
yield = -f0;
else
yield = f0;
if (dg(yield) ) break ;
auto temp = f1;
f1 = f0 + f1;
f0 = temp;
}
return 0 ;
}
} ;
}

void main( in string [ ] args) {
int k = args.length > 1 ? to! int (args[ 1 ] ) : 10 ;
writefln( "Fib(%3d) = " , k) ;
writefln( "D : %20d <- %20d + %20d" ,
sfibD(k) , sfibD(k - 1 ) , sfibD(k - 2 ) ) ;
writefln( "I : %20d <- %20d + %20d" ,
sfibI(k) , sfibI(k - 1 ) , sfibI(k - 2 ) ) ;
if (abs(k) < 36 || args.length > 2 )
// set a limit for recursive version
writefln( "R : %20d <- %20d + %20d" ,
sfibR(k) , sfibM(k - 1 ) , sfibM(k - 2 ) ) ;
writefln( "O : %20d <- %20d + %20d" ,
sfibM(k) , sfibM(k - 1 ) , sfibM(k - 2 ) ) ;
foreach (i, f; fibG( - 9 ) )
writef( "%d:%d | " , i, f) ;
}

for n = 85:

Fib( 85) =  D :   259695496911122586 <-   160500643816367088 +    99194853094755497 I :   259695496911122585 <-   160500643816367088 +    99194853094755497 O :   259695496911122585 <-   160500643816367088 +    99194853094755497 0:0 | -1:1 | -2:-1 | -3:2 | -4:-3 | -5:5 | -6:-8 | -7:13 | -8:-21 | -9:34 |        

Matrix Exponentiation Version [edit]

          import          std.bigint          ;          

 T fibonacciMatrix(T=BigInt) ( size_t n) {
int [ size_t.sizeof * 8 ] binDigits;
size_t nBinDigits;
while (n > 0 ) {
binDigits[nBinDigits] = n % 2 ;
n /= 2 ;
nBinDigits++;
}

  T x= 1 , y, z= 1 ;
foreach_reverse (b; binDigits[ 0 .. nBinDigits ] ) {
if (b) {
x = (x + z) * y;
y = y ^^ 2 + z ^^ 2 ;
} else {
auto x_old = x;
x = x ^^ 2 + y ^^ 2 ;
y = (x_old + z) * y;
}
z = x + y;
}

  return y;
}

void main( ) {
10_000_000.fibonacciMatrix ;
}

Faster Version [edit]

For N = 10_000_000 this is about twice faster (run-time about 2.20 seconds) than the matrix exponentiation version.

          import          std.bigint          ,          std.math          ;          

// Algorithm from: Takahashi, Daisuke,
// "A fast algorithm for computing large Fibonacci numbers".
// Information Processing Letters 75.6 (30 November 2000): 243-246.
// Implementation from:
// pythonista.wordpress.com/2008/07/03/pure-python-fibonacci-numbers
BigInt fibonacci( in ulong n)
in {
assert (n > 0 , "fibonacci(n): n must be > 0." ) ;
} body {
if (n <= 2 )
return 1.BigInt ;
BigInt F = 1 ;
BigInt L = 1 ;
int sign = - 1 ;
immutable uint n2 = cast ( uint )n.log2.floor ;
auto mask = 2.BigInt ^^ (n2 - 1 ) ;
foreach ( immutable i; 1 .. n2 ) {
auto temp = F ^^ 2 ;
F = (F + L) / 2 ;
F = 2 * F ^^ 2 - 3 * temp - 2 * sign;
L = 5 * temp + 2 * sign;
sign = 1 ;
if (n & mask) {
temp = F;
F = (F + L) / 2 ;
L = F + 2 * temp;
sign = - 1 ;
}
mask /= 2 ;
}
if ( (n & mask) == 0 ) {
F *= L;
} else {
F = (F + L) / 2 ;
F = F * L - sign;
}
return F;
}

void main( ) {
10_000_000.fibonacci ;
}

Dart [edit]

int fib(int n) {
if (n==0 || n==1) {
return n;
}
var prev=1;
var current=1;
for (var i=2; i<n; i++) {
var next = prev + current;
prev = current;
current = next;
}
return current;
}

 int fibRec(int n) => n==0 || n==1 ? n : fibRec(n-1) + fibRec(n-2);

 main() {
print(fib(11));
print(fibRec(11));
}

Datalog [edit]

Simple recurive implementation for Souffle.

.decl Fib(i:number, x:number)
Fib(0, 0).
Fib(1, 1).
Fib(i+2,x+y) :- Fib(i+1, x), Fib(i, y), i+2<=40, i+2>=2.
Fib(i-2,y-x) :- Fib(i-1, x), Fib(i, y), i-2>=-40, i-2<0.

DBL [edit]

;
; Fibonacci sequence for DBL version 4 by Dario B.
;
RECORD

 FIB1, D10
FIB2, D10
FIBN, D10

 J, D5
A2, A2
A5, A5
PROC
;----------------------------------------------------------------
XCALL FLAGS (0007000000,1)  ;Suppress STOP message

  OPEN (1,O,'TT:')
DISPLAY (1,'First 10 Fibonacci Numbers:',10)

  FIB2=1

  FOR J=1 UNTIL 10
DO BEGIN
FIBN=FIB1+FIB2

  A2=J,'ZX'
A5=FIBN,'ZZZZX'
DISPLAY (1,A2,' : ',A5,10)

  FIB1=FIB2
FIB2=FIBN
END

  CLOSE 1
END

Dc [edit]

This needs a modern Dc with r (swap) and # (comment). It easily can be adapted to an older Dc, but it will impact readability a lot.

[               # todo: n(<2) -- 1 and break 2 levels
d - # 0
1 + # 1
q
] s1

 [ # todo: n(>-1) -- F(n)
d 0=1 # n(!=0)
d 1=1 # n(!in {0,1})
2 - d 1 + # (n-2) (n-1)
lF x # (n-2) F(n-1)
r # F(n-1) (n-2)
lF x # F(n-1)+F(n-2)
+
] sF

 33 lF x f

5702887        

Delphi [edit]

Iterative [edit]


function FibonacciI(N: Word ) : UInt64;
var
Last, New: UInt64;
I: Word ;
begin
if N < 2 then
Result : = N
else begin
Last : = 0 ;
Result : = 1 ;
for I : = 2 to N do
begin
New : = Last + Result;
Last : = Result;
Result : = New;
end ;
end ;
end ;

Recursive [edit]


function Fibonacci(N: Word ) : UInt64;
begin
if N < 2 then
Result : = N
else
Result : = Fibonacci(N - 1 ) + Fibonacci(N - 2 ) ;
end ;

Matrix [edit]

Algorithm is based on

( 1 1 1 0 ) n = ( F ( n + 1 ) F ( n ) F ( n ) F ( n 1 ) ) {\displaystyle {\begin{pmatrix}1&1\\1&0\end{pmatrix}}^{n}={\begin{pmatrix}F(n+1)&F(n)\\F(n)&F(n-1)\end{pmatrix}}} .

function fib(n: Int64 ) : Int64 ;

  type TFibMat = array [ 0 .. 1 ] of array [ 0 .. 1 ] of Int64 ;

  function FibMatMul(a,b: TFibMat) : TFibMat;
var i,j,k: integer ;
tmp: TFibMat;
begin
for i : = 0 to 1 do
for j : = 0 to 1 do
begin
tmp[i,j] : = 0 ;
for k : = 0 to 1 do tmp[i,j] : = tmp[i,j] + a[i,k] * b[k,j] ;
end ;
FibMatMul : = tmp;
end ;

  function FibMatExp(a: TFibMat; n: Int64 ) : TFibmat;
begin
if n <= 1 then fibmatexp : = a
else if (n mod 2 = 0 ) then FibMatExp : = FibMatExp(FibMatMul(a,a) , n div 2 )
else if (n mod 2 = 1 ) then FibMatExp : = FibMatMul(a, FibMatExp(FibMatMul(a,a) , n div 2 ) ) ;
end ;

var
matrix: TFibMat;

begin
matrix[ 0 , 0 ] : = 1 ;
matrix[ 0 , 1 ] : = 1 ;
matrix[ 1 , 0 ] : = 1 ;
matrix[ 1 , 1 ] : = 0 ;
if n > 1 then
matrix : = fibmatexp(matrix,n- 1 ) ;
fib : = matrix[ 0 , 0 ] ;
end ;

DIBOL-11 [edit]

  START  ;First 10 Fibonacci NUmbers

   RECORD
FIB1, D10, 0
FIB2, D10, 1
FIBNEW, D10
LOOPCNT, D2, 1

  RECORD HEADER
, A32, "First 10 Fibonacci Numbers."

  RECORD OUTPUT
LOOPOUT, A2
, A3, " : "
FIBOUT, A10

  PROC

  OPEN(8,O,'TT:')

  WRITES(8,HEADER)

  LOOP,
FIBNEW = FIB1 + FIB2
LOOPOUT = LOOPCNT, 'ZX'
FIBOUT = FIBNEW, 'ZZZZZZZZZX'

  WRITES(8,OUTPUT)

  FIB1 = FIB2
FIB2 = FIBNEW

  LOOPCNT = LOOPCNT + 1
IF LOOPCNT .LE. 10 GOTO LOOP

  CLOSE 8
END

DWScript [edit]

          function          fib(N          :          Integer          )          :          Integer          ;          
begin
if N < 2 then Result : = 1
else Result : = fib(N- 2 ) + fib(N- 1 ) ;
End ;

Dyalect [edit]

func fib(n) {
if n < 2 {
return n
} else {
return fib(n - 1) + fib(n - 2)
}
}

 print(fib(30))

E [edit]

          def          fib(n)          {          
var s := [ 0 , 1 ]
for _ in 0..!n {
def [a, b] := s
s := [b, a+b]
}
return s[ 0 ]
}

(This version defines fib(0) = 0 because OEIS A000045 does.)

EasyLang [edit]

func fib n . b .
a = 0
b = 1
while n > 1
h = a + b
a = b
b = h
n -= 1
.
.
call fib 30 r
print r

EchoLisp [edit]

Use memoization with the recursive version.


( define (fib n)
( if ( < n 2 ) n
( + (fib ( - n 2 ) ) (fib ( 1 - n) ) ) ) )

(remember 'fib #( 0 1 ) )

(for ( (i 12 ) ) ( write (fib i) ) )
0 1 1 2 3 5 8 13 21 34 55 89

ECL [edit]

Analytic [edit]

//Calculates Fibonacci sequence up to n steps using Binet's closed form solution

  FibFunction(UNSIGNED2 n) := FUNCTION
REAL Sqrt5 := Sqrt(5);
REAL Phi := (1+Sqrt(5))/2;
REAL Phi_Inv := 1/Phi;
UNSIGNED FibValue := ROUND( ( POWER(Phi,n)-POWER(Phi_Inv,n) ) /Sqrt5);
RETURN FibValue;
END;

  FibSeries(UNSIGNED2 n) := FUNCTION

  Fib_Layout := RECORD
UNSIGNED5 FibNum;
UNSIGNED5 FibValue;
END;

  FibSeq := DATASET(n+1,
TRANSFORM
( Fib_Layout
, SELF.FibNum := COUNTER-1
, SELF.FibValue := IF(SELF.FibNum<2,SELF.FibNum, FibFunction(SELF.FibNum) )
)
);

  RETURN FibSeq;

  END; }

EDSAC order code [edit]

This program calculates the nth—by default the tenth—number in the Fibonacci sequence and displays it (in binary) in the first word of storage tank 3.

[ Fibonacci sequence
==================

  A program for the EDSAC

  Calculates the nth Fibonacci
number and displays it at the
top of storage tank 3

  The default value of n is 10

  To calculate other Fibonacci
numbers, set the starting value
of the count to n-2

  Works with Initial Orders 2 ]

   T56K [ set load point ]
GK [ set theta ]

 [ Orders ]

 [ 0 ] [email protected] [ a = 0 ]
[email protected] [ a += y ]
[email protected] [ temp = a ]
[email protected] [ a += x ]
[email protected] [ y = a; a = 0 ]
[email protected] [ a += temp ]
[email protected] [ x = a; a = 0 ]

  [email protected] [ a = count ]
[email protected] [ a -= 1 ]
[email protected] [ count = a ]
[email protected] [ if a>=0 go to θ ]

  [email protected] [ a = 0 ]
[email protected] [ a += y ]
T96F [ C(96) = a; a = 0]

  ZF [ halt ]

 [ Data ]

 [ 15 ] P0D [ const: 1 ]
[ 16 ] P0F [ var: x = 0 ]
[ 17 ] P0D [ var: y = 1 ]
[ 18 ] P0F [ var: temp = 0 ]
[ 19 ] P4F [ var: count = 8 ]
[ 20 ] P0F [ used to clear a ]

  EZPF [ begin execution ]

00000000000110111

Eiffel [edit]


class
APPLICATION

create
make

feature

  fibonacci (n: INTEGER ) : INTEGER
require
non_negative: n >= 0
local
i, n2, n1, tmp: INTEGER
do
n2 := 0
n1 := 1
from
i := 1
until
i >= n
loop
tmp := n1
n1 := n2 + n1
n2 := tmp
i := i + 1
end
Result := n1
if n = 0 then
Result := 0
end
end

feature { NONE } -- Initialization

  make
-- Run application.
do
print (fibonacci ( 0 ) )
print ( " " )
print (fibonacci ( 1 ) )
print ( " " )
print (fibonacci ( 2 ) )
print ( " " )
print (fibonacci ( 3 ) )
print ( " " )
print (fibonacci ( 4 ) )
print ( "%N" )
end

end

Ela [edit]

Tail-recursive function:

fib = fib' 0 1          
where fib' a b 0 = a
fib' a b n = fib' b (a + b) (n - 1)

Infinite (lazy) list:

fib = fib' 1 1
where fib' x y = & x :: fib' y (x + y)

Elena [edit]

Translation of: Smalltalk

ELENA 5.0 :

import extensions;

 fibu(n)
{
int[] ac := new int[]{ 0,1 };
if (n < 2)
{
^ ac[n]
}
else
{
for(int i := 2, i <= n, i+=1)
{
int t := ac[1];
ac[1] := ac[0] + ac[1];
ac[0] := t
};

  ^ ac[1]
}
}

 public program()
{
for(int i := 0, i <= 10, i+=1)
{
console.printLine(fibu(i))
}
}

0 1 1 2 3 5 8 13 21 34 55        

Alternative version using yieldable method [edit]

import extensions;

 public FibonacciGenerator
{
yieldable next()
{
long n_2 := 1l;
long n_1 := 1l;

  yield:n_2;
yield:n_1;

  while(true)
{
long n := n_2 + n_1;

  yield:n;

  n_2 := n_1;
n_1 := n
}
}
}

 public program()
{
auto e := new FibonacciGenerator();

  for(int i := 0, i < 10, i += 1) {
console.printLine(e.next())
};

  console.readChar()
}

Elixir [edit]

defmodule Fibonacci do
def fib(0), do: 0
def fib(1), do: 1
def fib(n), do: fib(0, 1, n-2)

  def fib(_, prv, -1), do: prv
def fib(prvprv, prv, n) do
next = prv + prvprv
fib(prv, next, n-1)
end
end

 IO.inspect Enum.map(0..10, fn i-> Fibonacci.fib(i) end)

Using Stream:


Stream.unfold({0,1}, fn {a,b} -> {a,{b,a+b}} end) |> Enum.take(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]        

Elm [edit]

Naïve recursive implementation.

fibonacci :          Int          ->          Int          
fibonacci n = if n < 2 then
n
else
fibonacci(n - 2 ) + fibonacci(n - 1 )

Emacs Lisp [edit]

version 1 [edit]


(defun fib (n a b c)
(if (< c n) (fib n b (+ a b) (+ 1 c) )
(if (= c n) b a) ))

 (defun fibonacci (n) (if (< n 2) n (fib n 0 1 1) ))

version 2 [edit]


(defun fibonacci (n)
(let ( (vec) (i) (j) (k) )
(if (< n 2) n
(progn
(setq vec (make-vector (+ n 1) 0) i 0 j 1 k 2)
(setf (aref vec 1) 1)
(while (<= k n)
(setf (aref vec k) (+ (elt vec i) (elt vec j) ))
(setq i (+ 1 i) j (+ 1 j) k (+ 1 k) ))
(elt vec n) ))))

Eval:


(insert
(mapconcat '(lambda (n) (format "%d" (fibonacci n) ))
(number-sequence 0 15) " ") )

Output:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610        

Erlang [edit]

Recursive [edit]


- module (fib) .
- export ( [fib/ 1 ] ) .

fib ( 0 ) -> 0 ;
fib ( 1 ) -> 1 ;
fib ( N ) -> fib ( N - 1 ) + fib ( N - 2 ) .

Iterative [edit]


- module (fiblin) .
- export ( [fib/ 1 ] )

fib ( 0 ) -> 0 ;
fib ( 1 ) -> 1 ;
fib ( 2 ) -> 1 ;
fib ( 3 ) -> 2 ;
fib ( 4 ) -> 3 ;
fib ( 5 ) -> 5 ;

fib ( N ) when is_integer ( N ) -> fib ( N - 6 , 5 , 8 ) .
fib ( N , A , B ) -> if N < 1 -> B ; true -> fib ( N - 1 , B , A + B ) end .

Evaluate:


io:write ( [fiblin:fib ( X ) || X <- lists:seq ( 1 , 10 ) ] ) .

Output:

          [1,1,2,3,5,8,13,21,34,55]ok        

Iterative 2 [edit]


fib ( N ) -> fib ( N , 0 , 1 ) .

fib ( 0 , Result , _Next ) -> Result ;
fib ( Iter , Result , Next ) -> fib ( Iter - 1 , Next , Result + Next ) .

ERRE [edit]

!-------------------------------------------
! derived from my book "PROGRAMMARE IN ERRE"
! iterative solution
!-------------------------------------------

 PROGRAM FIBONACCI

 !$DOUBLE

 !VAR F1#,F2#,TEMP#,COUNT%,N%

 BEGIN  !main
INPUT("Number",N%)
F1=0
F2=1
REPEAT
TEMP=F2
F2=F1+F2
F1=TEMP
COUNT%=COUNT%+1
UNTIL COUNT%=N%
PRINT("FIB(";N%;")=";F2)

   ! Obviously a FOR loop or a WHILE loop can
! be used to solve this problem

 END PROGRAM

Number? 20 FIB( 20 )= 6765        

Euphoria [edit]

'Recursive' version [edit]

Works with: Euphoria version any version


function fibor( integer n)
if n<2 then return n end if
return fibor(n- 1 ) +fibor(n- 2 )
end function

'Iterative' version [edit]

Works with: Euphoria version any version


function fiboi( integer n)
integer f0= 0 , f1= 1 , f
if n<2 then return n end if
for i= 2 to n do
f=f0+f1
f0=f1
f1=f
end for
return f
end function

'Tail recursive' version [edit]

Works with: Euphoria version 4.0.0


function fibot( integer n, integer u = 1 , integer s = 0 )
if n < 1 then
return s
else
return fibot(n- 1 ,u+s,u)
end if
end function

-- example:
? fibot( 10 ) -- says 55

'Paper tape' version [edit]

Works with: Euphoria version 4.0.0


include std/mathcons.e -- for PINF constant

 enum ADD, MOVE, GOTO, OUT, TEST, TRUETO

global sequence tape = { 0 ,
1 ,
{ ADD, 2 , 1 } ,
{ TEST, 1 , PINF } ,
{ TRUETO, 0 } ,
{ OUT, 1 , "%.0f\n" } ,
{ MOVE, 2 , 1 } ,
{ MOVE, 0 , 2 } ,
{ GOTO, 3 } }

global integer ip
global integer test
global atom accum

procedure eval( sequence cmd )
atom i = 1
while i <= length ( cmd ) do
switch cmd[ i ] do
case ADD then
accum = tape[ cmd[ i + 1 ] ] + tape[ cmd[ i + 2 ] ]
i += 2

  case OUT then
printf ( 1 , cmd[ i + 2 ] , tape[ cmd[ i + 1 ] ] )
i += 2

  case MOVE then
if cmd[ i + 1 ] = 0 then
tape[ cmd[ i + 2 ] ] = accum
else
tape[ cmd[ i + 2 ] ] = tape[ cmd[ i + 1 ] ]
end if
i += 2

  case GOTO then
ip = cmd[ i + 1 ] - 1 -- due to ip += 1 in main loop
i += 1

  case TEST then
if tape[ cmd[ i + 1 ] ] = cmd[ i + 2 ] then
test = 1
else
test = 0
end if
i += 2

  case TRUETO then
if test then
if cmd[ i + 1 ] = 0 then
abort ( 0 )
else
ip = cmd[ i + 1 ] - 1
end if
end if

  end switch
i += 1
end while
end procedure

 test = 0
accum = 0
ip = 1

while 1 do

  -- embedded sequences (assumed to be code) are evaluated
-- atoms (assumed to be data) are ignored

  if sequence ( tape[ ip ] ) then
eval( tape[ ip ] )
end if
ip += 1
end while

Excel [edit]

LAMBDA [edit]

Binding the name FIBONACCI to the following lambda in the Excel worksheet Name Manager:

(See The LAMBDA worksheet function)

FIBONACCI
= LAMBDA (n,
APPLYN(n - 2 ) (
LAMBDA (xs,
APPENDROWS(xs) (
SUM(
LASTNROWS( 2 ) (xs)
)
)
)
) ( { 1 ;1})
)

And assuming that the following names are also bound to reusable generic lambdas in the Name manager:

APPENDROWS
= LAMBDA (xs,
LAMBDA (ys,
LET (
nx, ROWS(xs) ,
rowIndexes, SEQUENCE(nx + ROWS(ys) ) ,
colIndexes, SEQUENCE(
1 ,
MAX (COLUMNS(xs) , COLUMNS(ys) )
) ,

  IFERROR(
IF (rowIndexes <= nx,
INDEX(xs, rowIndexes, colIndexes) ,
INDEX(ys, rowIndexes - nx, colIndexes)
) ,
NA( )
)
)
)
)

  APPLYN
= LAMBDA (n,
LAMBDA (f,
LAMBDA (x,
IF ( 0 < n,
APPLYN(n - 1 ) (f) (
f(x)
) ,
x
)
)
)
)

 LASTNROWS
= LAMBDA (n,
LAMBDA (xs,
LET (
nRows, COUNTA(xs) ,
x, MIN (nRows, n) ,

  IF ( 0 < n,
INDEX(
xs,
SEQUENCE(
x, 1 ,
1 + nRows - x, 1
)
) ,
NA( )
)
)
)
)

The FIBONACCI(n) lambda defines a column of integers.

Here we obtain a row, by composing FIBONACCI with the built-in TRANSPOSE function:

fx =TRANSPOSE(FIBONACCI(15))
A B C D E F G H I J K L M N O P
1
2 15 Fibonacci terms: 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

Or as a fold, obtaining just the Nth term of the Fibonacci series:

FIBONACCI2
= LAMBDA (n,
INDEX(
FOLDL(
LAMBDA (ab,
LAMBDA (_,
APPEND (INDEX(ab, 2 ) ) (SUM(ab) )
)
)
) ( { 0 ;1})(
ENUMFROMTO( 1 ) (n)
) ,
1
)
)

Assuming the following generic bindings in the Excel worksheet Name manager:

          APPEND          
= LAMBDA (xs,
LAMBDA (ys,
LET (
nx, ROWS(xs) ,
rowIndexes, SEQUENCE(nx + ROWS(ys) ) ,
colIndexes, SEQUENCE(
1 ,
MAX (COLUMNS(xs) , COLUMNS(ys) )
) ,
IF (rowIndexes <= nx,
INDEX(xs, rowIndexes, colIndexes) ,
INDEX(ys, rowIndexes - nx, colIndexes)
)
)
)
)

  ENUMFROMTO
= LAMBDA (a,
LAMBDA (z,
SEQUENCE( 1 + z - a, 1 , a, 1 )
)
)

  FOLDL
= LAMBDA (op,
LAMBDA (a,
LAMBDA (xs,
IF (
2 > ROWS(xs) ,
op(a) (xs) ,
FOLDL(op) (
op(a) (
HEAD(xs)
)
) (
TAIL(xs)
)
)
)
)
)

  HEAD
= LAMBDA (xs,
INDEX(xs, 1 , SEQUENCE( 1 , COLUMNS(xs) ) )
)

  TAIL
= LAMBDA (xs,
INDEX(
xs,
SEQUENCE(ROWS(xs) - 1 , 1 , 2 , 1 ) ,
SEQUENCE( 1 , COLUMNS(xs) )
)
)

fx =FIBONACCI2(A2)
A B
1 N Fibonacci
2 32 2178309
3 64 10610209857723

F# [edit]

This is a fast [tail-recursive] approach using the F# big integer support:


let fibonacci n : bigint =
let rec f a b n =
match n with
| 0 -> a
| 1 -> b
| n -> (f b (a + b) (n - 1 ) )
f (bigint 0 ) (bigint 1 ) n
> fibonacci 100 ;;
val it : bigint = 354224848179261915075I

Lazy evaluated using sequence workflow:

          let          rec          fib          =          seq          {          yield!          [          0          ;          1          ]          ;          
for (a,b) in Seq.zip fib ( Seq.skip 1 fib) -> a+b}

The above is extremely slow due to the nested recursions on sequences, which aren't very efficient at the best of times. The above takes seconds just to compute the 30th Fibonacci number!

Lazy evaluation using the sequence unfold anamorphism is much much better as to efficiency:

          let          fibonacci          =          Seq.unfold          (          fun          (x, y)          ->          Some(x,          (y, x          +          y)          )          )          (0I,1I)          
fibonacci |> Seq.nth 10000

Approach similar to the Matrix algorithm in C#, with some shortcuts involved. Since it uses exponentiation by squaring, calculations of fib(n) where n is a power of 2 are particularly quick. Eg. fib(2^20) was calculated in a little over 4 seconds on this poster's laptop.


open System
open System.Diagnostics
open System.Numerics

/// Finds the highest power of two which is less than or equal to a given input.
let inline prevPowTwo (x : int ) =
let mutable n = x
n <- n - 1
n <- n ||| (n >>> 1 )
n <- n ||| (n >>> 2 )
n <- n ||| (n >>> 4 )
n <- n ||| (n >>> 8 )
n <- n ||| (n >>> 16 )
n <- n + 1
match x with
| x when x = n -> x
| _ -> n/ 2

/// Evaluates the nth Fibonacci number using matrix arithmetic and
/// exponentiation by squaring.
let crazyFib (n : int ) =
let powTwo = prevPowTwo n

  /// Applies 2n rule repeatedly until another application of the rule would
/// go over the target value (or the target value has been reached).
let rec iter1 i q r s =
match i with
| i when i < powTwo ->
iter1 (i* 2 ) (q*q + r*r) (r * (q+s) ) (r*r + s*s)
| _ -> i, q, r, s

  /// Applies n+1 rule until the target value is reached.
let rec iter2 (i, q, r, s) =
match i with
| i when i < n ->
iter2 ( (i+ 1 ), (q+r), q, r)
| _ -> q

  match n with
| 0 -> 1I
| _ ->
iter1 1 1I 1I 0I
|> iter2

Factor [edit]

Iterative [edit]

: fib ( n -- m )
dup 2 < [
[ 0 1 ] dip [ swap [ + ] keep ] times
drop
] unless ;

Recursive [edit]

: fib ( n -- m )
dup 2 < [
[ 1 - fib ] [ 2 - fib ] bi +
] unless ;

Tail-Recursive [edit]

: fib2 ( x y n -- a )
dup 1 <
[ 2drop ]
[ [ swap [ + ] keep ] dip 1 - fib2 ]
if ;
: fib ( n -- m ) [ 0 1 ] dip fib2 ;

Matrix [edit]

Translation of: Ruby

USE: math.matrices

 : fib ( n -- m )
dup 2 < [
[ { { 0 1 } { 1 1 } } ] dip 1 - m^n
second second
] unless ;

Falcon [edit]

Iterative [edit]

          function          fib_i(n)          

  if n < 2 : return n

  fibPrev = 1
fib = 1
for i in [ 2 :n]
tmp = fib
fib += fibPrev
fibPrev = tmp
end
return fib
end

Recursive [edit]

          function          fib_r(n)          
if n < 2 : return n
return fib_r(n- 1 ) + fib_r(n- 2 )
end

Tail Recursive [edit]

          function          fib_tr(n)          
return fib_aux(n, 0 , 1 )
end
function fib_aux(n,a,b)
switch n
case 0 : return a
default : return fib_aux(n- 1 ,a+b,a)
end
end

FALSE [edit]

[[$0=~][[email protected]@\[email protected]@+\$44,[email protected]]#]f:
20n: {First 20 numbers}
0 1 n;f;!%%44,. {Output: "0,1,1,2,3,5..."}

Fancy [edit]

class Fixnum {
def fib {
match self -> {
case 0 -> 0
case 1 -> 1
case _ -> self - 1 fib + (self - 2 fib)
}
}
}

 15 times: |x| {
x fib println
}

Fantom [edit]

Ints have a limit of 64-bits, so overflow errors occur after computing Fib(92) = 7540113804746346429.


class Main
{
static Int fib (Int n)
{
if (n < 2) return n
fibNums := [1, 0]
while (fibNums.size <= n)
{
fibNums.insert (0, fibNums[0] + fibNums[1])
}
return fibNums.first
}

  public static Void main ()
{
20.times |n|
{
echo ("Fib($n) is ${fib(n)}")
}
}
}

Fermat [edit]

Func Fibonacci(n) = if n<0 then -(-1)^n*Fibonacci(-n) else if n<2 then n else          
Array fib[n+1];
fib[1] := 0;
fib[2] := 1;
for i = 2, n do
fib[i+1]:=fib[i]+fib[i-1]
od;
Return(fib[n+1]);
fi;
fi;
.

Fexl [edit]


# (fib n) = the nth Fibonacci number
\fib=
(
\loop==
(\x\y\n
le n 0 x;
\z=(+ x y)
\n=(- n 1)
loop y z n
)
loop 0 1
)

  # Now test it:
for 0 20 (\n say (fib n))

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765        

FOCAL [edit]

01.10 TYPE "FIBONACCI NUMBERS" !
01.20 ASK "N =", N
01.30 SET A=0
01.40 SET B=1
01.50 FOR I=2,N; DO 2.0
01.60 TYPE "F(N) ", %8, B, !
01.70 QUIT

 02.10 SET T=B
02.20 SET B=A+B
02.30 SET A=T

FIBONACCI NUMBERS N =:20 F(N) =    6765

Forth [edit]

: fib ( n -- fib )
0 1 rot 0 ?do over + swap loop drop ;

Or, for negative-index support:

: fib ( n -- Fn ) 0 1 begin
rot dup 0 = if drop drop exit then
dup 0 > if 1 - rot rot dup rot +
else 1 + rot rot over - swap then
again ;

Since there are only a fixed and small amount of Fibonacci numbers that fit in a machine word, this FORTH version creates a table of Fibonacci numbers at compile time. It stops compiling numbers when there is arithmetic overflow (the number turns negative, indicating overflow.)

: F-start,  here 1 0 dup , ;
: F-next, over + swap
dup 0> IF dup , true ELSE false THEN ;

 : computed-table ( compile: 'start 'next / run: i -- x )
create
>r execute
BEGIN [email protected] execute not UNTIL rdrop
does>
swap cells + @ ;

 ' F-start, ' F-next, computed-table fibonacci 2drop
here swap - cell/ Constant #F/64 \ # of fibonacci numbers generated

 16 fibonacci . 987 ok
#F/64 . 93 ok
92 fibonacci . 7540113804746346429 ok \ largest number generated.

Fortran [edit]

FORTRAN IV [edit]

          C     FIBONACCI SEQUENCE - FORTRAN IV          
NN= 46
DO 1 I= 0,NN
1 WRITE( *,300 ) I,IFIBO(I)
300 FORMAT(1X,I2,1X,I10)
END
C
FUNCTION IFIBO(N)
IF (N) 9,1,2
1 IFN= 0
GOTO 9
2 IF (N- 1 ) 9,3,4
3 IFN= 1
GOTO 9
4 IFNM1= 0
IFN= 1
DO 5 I= 2,N
IFNM2=IFNM1
IFNM1=IFN
5 IFN=IFNM1+IFNM2
9 IFIBO=IFN
END
          0          0   1          1   2          1   3          2   4          3   5          5   6          8   7         13   8         21   9         34  10         55 ...  45 1134903170  46 1836311903        

FORTRAN 77 [edit]


FUNCTION IFIB(N)
IF (N.EQ.0) THEN
ITEMP0= 0
ELSE IF (N.EQ.1) THEN
ITEMP0= 1
ELSE IF (N.GT.1) THEN
ITEMP1= 0
ITEMP0= 1
DO 1 I= 2,N
ITEMP2=ITEMP1
ITEMP1=ITEMP0
ITEMP0=ITEMP1+ITEMP2
1 CONTINUE
ELSE
ITEMP1= 1
ITEMP0= 0
DO 2 I=- 1,N,- 1
ITEMP2=ITEMP1
ITEMP1=ITEMP0
ITEMP0=ITEMP2-ITEMP1
2 CONTINUE
END IF
IFIB=ITEMP0
END

Test program


EXTERNAL IFIB
CHARACTER * 10 LINE
PARAMETER ( LINE = '----------' )
WRITE( *,900 ) 'N', 'F[N]', 'F[-N]'
WRITE( *,900 ) LINE, LINE, LINE
DO 1 N = 0, 10
WRITE( *,901 ) N, IFIB(N), IFIB( -N)
1 CONTINUE
900 FORMAT( 3 (X,A10) )
901 FORMAT( 3 (X,I10) )
END
          N       F[N]      F[-N]  ---------- ---------- ----------           0          0          0           1          1          1           2          1         -1           3          2          2           4          3         -3           5          5          5           6          8         -8           7         13         13           8         21        -21           9         34         34          10         55        -55        

Recursive [edit]

In ISO Fortran 90 or later, use a RECURSIVE function:

          module          fibonacci
contains
recursive function fibR(n) result (fib)
integer, intent ( in ) :: n
integer :: fib

  select case (n)
case ( : 0 ); fib = 0
case ( 1 ); fib = 1
case default; fib = fibR(n- 1 ) + fibR(n- 2 )
end select
end function fibR

Iterative [edit]

In ISO Fortran 90 or later:

          function          fibI(n)          
integer, intent ( in ) :: n
integer, parameter :: fib0 = 0, fib1 = 1
integer :: fibI, back1, back2, i

  select case (n)
case ( : 0 ); fibI = fib0
case ( 1 ); fibI = fib1

  case default
fibI = fib1
back1 = fib0
do i = 2, n
back2 = back1
back1 = fibI
fibI = back1 + back2
end do
end select
end function fibI
end module fibonacci

Test program

          program          fibTest
use fibonacci

  do i = 0, 10
print *, fibr(i), fibi(i)
end do
end program fibTest

0 0 1 1 1 1 2 2 3 3 5 5 8 8 13 13 21 21 34 34 55 55        

Free Pascal [edit]

See also: Pascal

          type          
/// domain for Fibonacci function
/// where result is within nativeUInt
// You can not name it fibonacciDomain,
// since the Fibonacci function itself
// is defined for all whole numbers
// but the result beyond F(n) exceeds high(nativeUInt).
fibonacciLeftInverseRange =
{$ifdef CPU64} 0..93 {$else} 0..47 {$endif} ;

{**
implements Fibonacci sequence iteratively

  \param n the index of the Fibonacci number to calculate
\returns the Fibonacci value at n
}


function fibonacci( const n: fibonacciLeftInverseRange) : nativeUInt;
type
/// more meaningful identifiers than simple integers
relativePosition = (previous, current, next) ;
var
/// temporary iterator variable
i: longword;
/// holds preceding fibonacci values
f: array [relativePosition] of nativeUInt;
begin
f[previous] : = 0 ;
f[current] : = 1 ;

  // note, in Pascal for-loop-limits are inclusive
for i : = 1 to n do
begin
f[next] : = f[previous] + f[current] ;
f[previous] : = f[current] ;
f[current] : = f[next] ;
end ;

  // assign to previous, bc f[current] = f[next] for next iteration
fibonacci : = f[previous] ;
end ;

FreeBASIC [edit]

Extended sequence coded big integer.

          'Fibonacci extended          
'Freebasic version 24 Windows
Dim Shared ADDQmod( 0 To 19 ) As Ubyte
Dim Shared ADDbool( 0 To 19 ) As Ubyte

For z As Integer=0 To 19
ADDQmod(z)=(z Mod 10+48 )
ADDbool(z)=(-( 10<=z) )
Next z

Function plusINT(NUM1 As String,NUM2 As String ) As String
Dim As Byte flag
#macro finish()
three=Ltrim (three,"0" )
If three="" Then Return "0"
If flag=1 Then Swap NUM2,NUM1
Return three
Exit Function