Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[ Copyright 2017 Stekeblad
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- -------------------------------------------------------------------------------------------------------------------------
- This is a small script that compares two fibonacci sequence algorithms.
- One is the classic school example of a recursive algorithm and the second one is one I wrote that is using a loop instead.
- Here is the results I got after some testing:
- The slow version starts to slow down at about fibN = 35 (2 seconds) and increases fast (15 seconds at 40, 30 minutes at 50)
- The fast one finishes in under a second for fibN = 200, the problem here is the variables overflow and starts to return negative results after 161
- ]]
- local arg = {...}
- if tonumber(arg[1]) then
- fibN = tonumber(arg[1])
- else
- error("Invalid parameter, give witch fibonacci number ot calculate")
- end
- function fib(n)
- if n==0 then return 0 end
- if n==1 then return 1 end
- return fib(n-1) + fib(n-2)
- end
- function fib2(n)
- if n==0 then return 0 end
- if n==1 then return 1 end
- local v1, v2, v3, m = 0, 1, 1, 1
- while (m < n) do
- v3 = v2 + v1
- v1 = v2
- v2 = v3
- m = m + 1
- end
- return v3
- end
- print ("calculating " .. fibN .."th fibonacci number..")
- local start = os.time()
- print("Fast version: " ..fib2(fibN))
- print("time: " .. os.time() - start)
- if arg[2] then
- print("Skipping slow version.")
- else
- start = os.time()
- print("Slow version: " .. fib(fibN))
- print("time: " .. os.time() - start)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement