factorial.js (7kyu 46)

Codewars 알고리즘 풀이


Problem

  • In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.
    • factorial(계승)은 n보다 작거나 같은 모든 양의 정수의 곱이다.
    • 수학에서 n!로 나타낸다.
  • By convention the value of 0! is 1.
    • 규칙에 따라, 0!은 1이다.
  • Write a function to calculate factorial for a given input.
    • 주어진 입력에 대한 factorial을 계산하는 함수를 작성한다.


For example:

0! = 1

1! = 1 * 1 = 1

2! = 2 * 1 = 2

3! = 3 * 2 * 1 = 6

4! = 4 * 3 * 2 * 1 = 24

5! = 5 * 4 * 3 * 2 * 1 = 120


Solution 01

function factorial(n) {
  let result = 1;
  
  for (let i = 2; i <= n; i++) {
    result *= i;
  }
  return result;
}

factorial(0);  // 1
factorial(1);  // 1
factorial(2);  // 2
factorial(3);  // 6
factorial(4);  // 24
factorial(5);  // 120


Solution 02

function factorial(n) {
  if (n <= 1) {
    return 1;
  } else {
    return n * factorial(n - 1);
  }
}

factorial(0);  // 1
factorial(1);  // 1
factorial(2);  // 2
factorial(3);  // 6
factorial(4);  // 24
factorial(5);  // 120


Solution 03

function factorial(n) {
  return n <= 1 ? 1 : n * factorial(n - 1);
}

factorial(0);  // 1
factorial(1);  // 1
factorial(2);  // 2
factorial(3);  // 6
factorial(4);  // 24
factorial(5);  // 120