From 382e441a29926ba7a683f6e4e816f7ccb4f35961 Mon Sep 17 00:00:00 2001 From: Matthew Ellison Date: Tue, 26 Mar 2019 00:58:54 -0400 Subject: [PATCH] Added getFib functions --- Algorithms.lua | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/Algorithms.lua b/Algorithms.lua index ab7cd80..78becec 100644 --- a/Algorithms.lua +++ b/Algorithms.lua @@ -172,6 +172,48 @@ function getDivisors(goalNumber) return divisors; end +--This function returns the numth Fibonacci number +function getFib(goalSubscript) + --Setup the variables + local fibNums = {1, 1, 0}; --A list to keep track of the Fibonacci Numbers. It need only be 3 long because we only need the one we are working on and the last 2 + + --If the number is <= 0 return 0 + if(goalSubscript <= 0) then + return 0; + end + + --Loop through the list, generating Fibonacci numbers until it finds the correct subscript + local fibLoc = 3; + while(fibLoc <= goalSubscript) do + fibNums[fibLoc % 3] = fibNums[(fibLoc - 1) % 3] + fibNums[(fibLoc - 2) % 3]; + fibLoc = fibLoc + 1; + end + + --Return the propper number + return fibNums[(fibLoc - 1) % 3]; +end + +function getLargeFib(goalSubscript) + local bigint = require "bigint"; + --Setup the variables + local fibNums = {bigint.new(1), bigint.new(1), bigint.new(0)}; + + --If the number <= 0 return 0 + if(goalSubscript <= 0) then + return bigint.new(0); + end + + --Loop through the list, generating Fibonacci numbers until it finds the correct subscript + local fibLoc = 3; + while(fibLoc <= goalSubscript) do + fibNums[fibLoc % 3] = bigint.add(fibNums[(fibLoc - 1) % 3], fibNums[(fibLoc - 2) % 3]); + fibLoc = fibLoc + 1; + end + + --Return the propper number + return fibNums[(fibLoc - 1) % 3]; +end + function getSum(ary) local sum = 0; --Holds the sum of all elements. Start at 0 because num+1 = num --Look through every element in the array and add the number to the running sum