find the factorial of a number in typescript

Using Recursion

index.ts
function factorialRecursive(num: number): number {
  if (num <= 1) {
    return 1;
  }
  return num * factorialRecursive(num - 1);
}

// Example usage
console.log(factorialRecursive(5)); // Output: 120
202 chars
10 lines

The above program calculates the factorial of a number using a recursive function. The function checks if the given number is less or equal to 1, in which case it returns 1. Otherwise, it multiplies the number with the factorial of its decrement (num-1) and returns the result.

Using Loops

index.ts
function factorialLoop(num: number): number {
  let result = 1;
  for (let i = 1; i <= num; i++) {
    result *= i;
  }
  return result;
}

// Example usage
console.log(factorialLoop(5)); // Output: 120
203 chars
11 lines

The above program calculates the factorial of a number using a loop. Here, we initialize the result to 1 and iterate from 1 to the given number (inclusive). In each iteration, we multiply the result with the loop variable (i) and update the result. At the end of the loop, we return the result which contains the factorial of the given number.

gistlibby LogSnag