R factorial() 函数 - 计算阶乘
R factorial() 函数用于计算正整数的阶乘。
阶乘是指从 1 乘到 n 的连乘积,记作 n!。在排列组合和概率计算中非常常见。
factorial() 函数语法格式如下:
factorial(x)
参数说明:
x 输入非负整数或整数向量。
实例
# 计算单个数值的阶乘
print(factorial(5)) # 5! = 120
print(factorial(0)) # 0! = 1(约定)
print(factorial(10)) # 10! = 3628800
# 对向量中的每个元素计算阶乘
x <- c(0, 1, 2, 3, 4, 5)
print(factorial(x))
print(factorial(5)) # 5! = 120
print(factorial(0)) # 0! = 1(约定)
print(factorial(10)) # 10! = 3628800
# 对向量中的每个元素计算阶乘
x <- c(0, 1, 2, 3, 4, 5)
print(factorial(x))
执行以上代码输出结果为:
[1] 120 [1] 1 [1] 3628800 [1] 1 1 2 6 24 120
factorial() 在计算排列数和组合数时经常与 choose() 配合使用:
实例
# 手动计算排列数 P(5, 3) = 5*4*3
n <- 5; k <- 3
permutation <- factorial(n) / factorial(n - k)
print(paste("P(5,3) =", permutation))
# 手动计算组合数 C(5, 3) = P(5,3) / 3!
combination <- permutation / factorial(k)
print(paste("C(5,3) =", combination))
# 对比 R 内置函数
print(choose(5, 3))
n <- 5; k <- 3
permutation <- factorial(n) / factorial(n - k)
print(paste("P(5,3) =", permutation))
# 手动计算组合数 C(5, 3) = P(5,3) / 3!
combination <- permutation / factorial(k)
print(paste("C(5,3) =", combination))
# 对比 R 内置函数
print(choose(5, 3))
执行以上代码输出结果为:
[1] "P(5,3) = 60" [1] "C(5,3) = 10" [1] 10

R 语言实例