Skip to content

Calculating Fibonacci numbers

Daisho Komiyama edited this page Apr 27, 2024 · 2 revisions

Fibonacci sequence 10 is calculated as follows,

start 1 -- 1st
0+1 = 1 -- 2nd
1+1 = 2 -- 3rd
1+2 = 3 -- 4th
2+3 = 5 -- 5th
3+5 = 8 -- 6th
5+8 = 13 -- 7th
8+13 = 21 -- 8th
13+21 = 34 -- 9th
21+34 = 55 -- 10th

In Haskell,

fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

Usage

fib 7
-- 13

fib 10
-- 55

Optimal way

f = 0 : 1 : zipWith (+) fib (tail fib)
-- f returns [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987...]
fib x = f !! x

Usage

fib 10 -- 55
fib 40 -- 102334155
fib 100 -- 354224848179261915075
Clone this wiki locally