Created
August 13, 2013 23:10
-
-
Save obikag/6226633 to your computer and use it in GitHub Desktop.
Fibonacci Number methods done in Lua. First two methods calculates the Fibonacci number (n), while the last method prints the Fibonacci number sequence 'n' times.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Recursive Method calculating Fibonacci Number for n | |
function fibRecursion(n) | |
if n == 0 then | |
return 0 | |
elseif n == 1 then | |
return 1 | |
else | |
return fibRecursion(n-1) + fibRecursion(n-2) | |
end | |
end | |
-- Method containing a Loop that caluclates Fibonacci Number for n | |
function fibLoop(n) | |
if n == 0 then | |
return 0 | |
elseif n == 1 or n == 2 then | |
return 1 | |
else | |
local fib1, fib2, fib = 1, 1, 1 | |
for i = 3,n do | |
fib = fib1 + fib2 | |
fib1 = fib2 | |
fib2 = fib | |
end | |
return fib | |
end | |
end | |
-- Method that prints Fibonacci Number sequence n times | |
function fibSequence(n) | |
if(n < 0) then | |
return "Parameter must be a positive number" | |
else | |
local results = "" | |
for i = 0,n-1 do -- First number is 0 | |
if i == n-1 then | |
results = results..fibRecursion(i) --No comma is added if last number | |
else | |
results = results..fibRecursion(i)..", " | |
end | |
end | |
return "Fibonacci Sequence of the first "..n.." numbers is "..results | |
end | |
end | |
-- Test Section | |
print("Recurssion; fib(10): "..fibRecursion(10)) -- 55 | |
print("Loop; fib(10): "..fibLoop(10)) -- 55 | |
print(fibSequence(10)) -- Fibonacci Sequence of the first 10 numbers is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment