From 7ef12495c4ce3bedce18505c908520fc4576d3ff Mon Sep 17 00:00:00 2001 From: Mattrixwv Date: Tue, 1 Jun 2021 18:31:32 -0400 Subject: [PATCH] Added function to get factorial of number --- Algorithms.ts | 16 ++++++++++++++++ TestAlgorithms.ts | 30 +++++++++++++++++++++++++++++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/Algorithms.ts b/Algorithms.ts index 97838d5..7c47211 100644 --- a/Algorithms.ts +++ b/Algorithms.ts @@ -642,3 +642,19 @@ export function gcdBig(num1: bigint, num2: bigint){ } return num1 | num2; } + +//Return the factorial of the number passed in +export function factorial(num: number): number{ + let fact: number = 1; + for(let cnt = 1;cnt <= num;++cnt){ + fact *= cnt; + } + return fact; +} +export function factorialBig(num: bigint): bigint{ + let fact: bigint = 1n; + for(let cnt = 1n;cnt <= num;++cnt){ + fact *= cnt; + } + return fact; +} diff --git a/TestAlgorithms.ts b/TestAlgorithms.ts index 0bc1b21..d8970eb 100644 --- a/TestAlgorithms.ts +++ b/TestAlgorithms.ts @@ -23,7 +23,7 @@ Copyright (C) 2021 Matthew Ellison import assert = require("assert"); import { arrayEquals, getAllFib, getAllFibBig, getFactors, getFactorsBig, getPrimes, getPrimesBig, getNumPrimes, getNumPrimesBig, - sqrtBig, getSum, getSumBig, getProd, getProdBig, getDivisors, getDivisorsBig } from "./Algorithms"; + sqrtBig, getSum, getSumBig, getProd, getProdBig, getDivisors, getDivisorsBig, factorial, factorialBig } from "./Algorithms"; function testArrayEquals(){ @@ -205,6 +205,7 @@ function testGetSum(){ console.log("getSum passed"); } + function testGetProd(){ //Test 1 let correctAnswer: number = 0; @@ -226,6 +227,32 @@ function testGetProd(){ console.log("getProd passed"); } +function testFactorial(){ + //Test 1 + let num: number = 1; + let correctAnswer: number = 1; + let answer: number = factorial(num); + assert.ok((correctAnswer == answer), "factorial number 1 failed"); + //Test 2 + num = 10; + correctAnswer = 3628800; + answer = factorial(num); + assert.ok((correctAnswer == answer), "factorial number 2 failed"); + //Test 3 + num = -5; + correctAnswer = 1; + answer = factorial(num); + assert.ok((correctAnswer == answer), "factorial number 3 failed"); + + //Test 4 + let numBig: bigint = 1n; + let correctAnswerBig: bigint = 1n; + let answerBig = factorialBig(numBig); + assert.ok((correctAnswerBig == answerBig), "factorialBig number 1 failed"); + + console.log("factorial passed"); +} + //Run all of the tests testArrayEquals(); @@ -237,3 +264,4 @@ testGetFactors(); testGetDivisors(); testGetSum(); testGetProd(); +testFactorial();