mirror of
https://bitbucket.org/Mattrixwv/luaclasses.git
synced 2025-12-06 18:33:59 -05:00
Added function to comput factorial of number
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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");
|
||||
|
||||
Reference in New Issue
Block a user