diff --git a/Algorithms.hpp b/Algorithms.hpp index ca2ccdc..039b58a 100644 --- a/Algorithms.hpp +++ b/Algorithms.hpp @@ -576,6 +576,15 @@ std::vector split(std::string str, char delimiter){ return splitStrings; } +//Return the factorial of the number passed in +template +T factorial(T num){ + T fact = 1; + for(T cnt = 1;cnt <= num;++cnt){ + fact *= cnt; + } + return fact; +} } diff --git a/testAlgorithms.cpp b/testAlgorithms.cpp index 934b53f..c6492bb 100644 --- a/testAlgorithms.cpp +++ b/testAlgorithms.cpp @@ -53,15 +53,16 @@ bool testSearch(); bool testFindMin(); bool testFindMax(); bool testFindNumOccurrence(); +bool testFactorial(); int main(){ mee::Stopwatch timer; bool passedTest = false; std::vector functions {testGetPrimes, testGetNumPrimes, testIsPrime, testGetFactors, tetsGetDivisors, testGetSum, testGetProduct, testIsFound, testGetPermutations, - testGetFib, testGetAllFib, testBubbleSort, testQuickSort, testSearch, testFindMin, testFindMax, testFindNumOccurrence}; + testGetFib, testGetAllFib, testBubbleSort, testQuickSort, testSearch, testFindMin, testFindMax, testFindNumOccurrence, testFactorial}; std::vector names {"getPrimes", "getNumPrimes", "isPrime", "getFactors", "getDivisors", "getSum", "getProduct", "isFound", "getPermutations", - "getFib", "getAllFib", "bubbleSort", "quickSort", "search", "findMin", "findMax", "findNumOccurrence"}; + "getFib", "getAllFib", "bubbleSort", "quickSort", "search", "findMin", "findMax", "findNumOccurrence", "factorial"}; //Start doing tests and print out the results of each for(int cnt = 0;cnt < functions.size();++cnt){ @@ -482,6 +483,35 @@ bool testFindNumOccurrence(){ return true; } +bool testFactorial(){ + //Test 1 + int num = 1; + int correctAnswer = 1; + int answer = mee::factorial(num); + if(correctAnswer != answer){ + return false; + } + + //Test 2 + num = 10; + correctAnswer = 3628800; + answer = mee::factorial(num); + if(correctAnswer != answer){ + return false; + } + + //Test 3 + num = -5; + correctAnswer = 1; + answer = mee::factorial(num); + if(correctAnswer != answer){ + return false; + } + + //If it hasn't failed a test then return true for passing all the tests + return true; +} + /* Results: Function getPrimes() passed the test The test took 0.000 nanoseconds