一个数的阶乘是所有从 1 到该数的数字的乘积。例如:
5 的阶乘等于 1 * 2 * 3 * 4 * 5 = 120。
正数 n 的阶乘由下式给出:
factorial of n (n!) = 1 * 2 * 3 * 4.....n
负数的阶乘不存在,而 0 的阶乘是 1。
示例:使用递归查找阶乘
// program to find the factorial of a number
function factorial(x) {
// if number is 0
if (x == 0) {
return 1;
}
// if number is positive
else {
return x * factorial(x - 1);
}
}
// take input from the user
const num = prompt('Enter a positive number: ');
// calling factorial() if num is positive
if (num >= 0) {
const result = factorial(num);
console.log(`The factorial of ${num} is ${result}`);
}
else {
console.log('Enter a positive number.');
}
输出
Enter a positive number: 4 The factorial of 4 is 24
在上面的程序中,会提示用户输入一个数字。
当用户输入负数时,会显示消息 请输入正数。。
当用户输入正数或 0 时,会调用 factorial(num)
函数。
- 如果用户输入数字 0,程序将返回 1。
- 如果用户输入的数字大于 0,程序将通过递减数字来递归调用自身。
- 这个过程会一直持续到数字变为 1。然后当数字达到 0 时,返回 1。
这里,
factorial(4) returns 4 * factorial(3) factorial(3) returns 4 * 3 * factorial(2) factorial(2) returns 4 * 3 * 2 * factorial(1) factorial(1) returns 4 * 3 * 2 * 1 * factorial(0) factorial(0) returns 4 * 3 * 2 * 1 * 1
另请阅读