# 定义

一个正整数 n 的阶乘 (写作 n!), 就是所有小于等于 n的正整数的乘积

数学公式

f(0)=1f(0) = 1

f(n)=n(n1)...1f(n) = n * (n - 1) * ... * 1

Eg:

n! = 1 * 2 * ... * (n - 1)
1

fibonacci.png

# 实现代码

/*
 * @Author: Rainy
 * @Date: 2020-01-26 14:03:24
 * @LastEditors  : Rainy
 * @LastEditTime : 2020-01-26 14:27:27
 */
export function factorial(num: number): number {
  let result = 1;

  for (let i = 2; i <= num; i += 1) {
    result *= i;
  }

  // let count = 1;

  // while(count++ < num) {
  //   result *= count;
  // }

  return result;
}

export function factorialRecursive(num: number): number {
  return num > 1 ? num * factorialRecursive(num - 1) : 1;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 参考资料

阶乘 - wiki (opens new window)