Lua递归学习笔记,用于自己理解。
-- 普通递归
-- 普通递归
function fibon1(n)
if n < 3 then
return 1
end
return fibon1(n-2) + fibon1(n-1)
end
-- 尾递归
local function fibon_(n, n1, n2)
if n == 0 or n == 1 then
return n1
end
return fibon_(n-1, n2, n1 + n2)
end
function fibon2(nn)
return fibon_(nn, 1, 1)
end
-- 迭代
function fibon3(n)
local a, b = 1, 1
if n < 3 then
return 1
end
local c
for _ = 3, n do
c = a + b
a = b
b = c
end
return c
end
print(fibon3(40))
print(fibon2(40))
print(fibon1(40))