-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
fibonacci.nelua
42 lines (38 loc) · 945 Bytes
/
fibonacci.nelua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
require 'math'
do -- Recursive solution.
local function fibonacci(n: integer): integer
if n <= 2 then
return 1
end
return fibonacci(n - 1) + fibonacci(n - 2)
end
print(fibonacci(10))
end
do -- Tail recursive solution.
local function fibonacci(n: integer, current: integer, next: integer): integer
if n == 0 then
return current
end
return fibonacci(n - 1, next, current + next)
end
print(fibonacci(10, 0, 1))
end
do -- Iterative solution.
local function fibonacci(n: integer): integer
local first, second = 0, 1
for i=1,n do
first, second = second, first
second = second + first
end
return first
end
print(fibonacci(10))
end
do -- Analytic solution.
local function fibonacci(n: integer): integer
local p = (1.0 + math.sqrt(5.0)) / 2.0
local q = 1.0 / p
return (@integer)(math.floor((p^n + q^n) / math.sqrt(5.0)))
end
print(fibonacci(10))
end