Repository navigation
Expand file tree
/
Copy pathfibonacci.lua
More file actions
68 lines (59 loc) · 1.6 KB
/
Copy pathfibonacci.lua
File metadata and controls
68 lines (59 loc) · 1.6 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
local recursiveCalls = 0
local function parseN(raw)
local n = tonumber(raw)
if n == nil then
return nil, "n must be a number"
end
if n ~= math.floor(n) or n < 0 then
return nil, "n must be a non-negative integer"
end
return n
end
local function fibRecursive(n)
recursiveCalls = recursiveCalls + 1
if n <= 1 then
return n
end
return fibRecursive(n - 1) + fibRecursive(n - 2)
end
local function fibIterative(n)
if n <= 1 then
return n
end
local a, b = 0, 1
for _ = 2, n do
a, b = b, a + b
end
return b
end
local M = {
parseN = parseN,
fibRecursive = fibRecursive,
fibIterative = fibIterative,
}
if arg and arg[0] and tostring(arg[0]):find("fibonacci", 1, true) then
local n, err = parseN(arg[1] or "30")
if not n then
io.stderr:write(err .. "\n")
os.exit(1)
end
recursiveCalls = 0
local t1 = os.clock()
local r1 = fibRecursive(n)
local recursiveTime = os.clock() - t1
local t2 = os.clock()
local r2 = fibIterative(n)
local iterativeTime = os.clock() - t2
print("n =", n)
print("Recursive Fibonacci:", r1)
print("Recursive calls:", recursiveCalls)
print(string.format("Recursive time: %.6f seconds", recursiveTime))
print("Iterative Fibonacci:", r2)
print(string.format("Iterative time: %.6f seconds", iterativeTime))
if r1 ~= r2 then
io.stderr:write("recursive and iterative results differ\n")
os.exit(1)
end
print(string.format("Speedup: %.2fx", recursiveTime / math.max(iterativeTime, 1e-9)))
end
return M