diff --git a/Algorithms.lua b/Algorithms.lua index ec745df..09cb295 100644 --- a/Algorithms.lua +++ b/Algorithms.lua @@ -1,10 +1,10 @@ --luaClasses/Algorithms.lua --Matthew Ellison -- Created: 02-04-19 ---Modified: 03-28-19 +--Modified: 06-01-21 --This is a file of algorithms that I have found it useful to keep around at all times --[[ - Copyright (C) 2019 Matthew Ellison + Copyright (C) 2021 Matthew Ellison This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -353,3 +353,11 @@ function gcd(num1, num2) end return num1 | num2; end + +function factorial(num) + local fact = 1; + for cnt = 1, num do + fact = fact * cnt; + end + return fact; +end diff --git a/testAlgorithms.lua b/testAlgorithms.lua index a727f7e..a46052b 100644 --- a/testAlgorithms.lua +++ b/testAlgorithms.lua @@ -1,7 +1,7 @@ --lua/luaClasses/testAlgorithms.lua --Mathew Ellison -- Created: 03-28-19 ---Modified: 03-12-21 +--Modified: 06-01-21 --This script is used to test the Algorithms script --[[ Copyright (C) 2021 Matthew Ellison @@ -340,6 +340,37 @@ local function testGCD() end end +local function testFactorial() + local failed = false; --Signals whether a test was failed + + --Test 1 + local num = 1; + local correctAnswer = 1; + local answer = factorial(num); + if(answer ~= correctAnswer) then + io.write("factorial failed the first test\n"); + end + --Test 2 + local num = 10; + local correctAnswer = 3628800; + local answer = factorial(num); + if(answer ~= correctAnswer) then + io.write("factorial failed the second test\n"); + end + --Test 3 + local num = -5; + local correctAnswer = 1; + local answer = factorial(num); + if(answer ~= correctAnswer) then + io.write("factorial failed the third test\n"); + end + + --Print a message if all of the tests passed + if(not failed) then + io.write("factorial passed all tests\n"); + end +end + --Create the timer to time each test local timer = Stopwatch:create(); @@ -409,3 +440,9 @@ timer:start(); testGCD(); timer:stop(); io.write("It took " .. timer:getString() .. " to run this test\n"); + +--Test factorial +timer:start(); +testFactorial(); +timer:stop(); +io.write("It took " .. timer:getString() .. " to run this test\n");