Introduction
You can write a program to factorialize a number in Javascript using a recursive
function or for statement
.
Factorial in mathematics is the product of all positive integers less than or equal to a positive number. It is denoted by the integer
and an exclamation point. for example:
0! = 1
1! = 1
2! = 2 * 1
3! = 3 * 2 * 1
4! = 4 * 3 * 2 * 1
Factorial of a Number With For Statements (For Loop)
In this example, you will write the logic to multiply the given number by its number minus 1. To do this, define a function called factorial
that expects num
as a parameter.
function factorial(num) {
for (let i = num - 1; i >= 1; i--) {
num *= i;
}
return num;
}
factorial(6);
// 720
Breakdown
If you pass 6
as an argument to the factorial()
function, the following steps happen:
- The variable
i
value is5
6
(num
) is multiplied by5
(num - 1
) and new value of thenum
is equal to30
.30
is multiplied by4
, and the new value ofnum
is equal to120
.120
is multiplied by3
, and the new value ofnum
is equal to360
.360
is multiplied by2
, and the new value ofnum
is equal to720
.720
is multiplied by1
, and the new value ofnum
is equal to720
.- Program exits the loop
factorial()
function returns thenum
which is equal to720
.
Now you need to write the logic to handle the negative numbers, and 0
.
function factorial(num) {
if (num < 0) {
console.log("Number must be greater than or equal to 0");
} else if (num === 0) {
return 1;
} else {
for (let i = num - 1; i >= 1; i--) {
num *= i;
}
return num;
}
}
factorial(-1);
// Number must be greater than or equal to 0
factorial(0);
// 1
factorial(6);
// 720
Factorial of a Number Using Recursive Functions
Writing a recursive function to return the factorial of a number is similar to what you did with For Statements
in the previous step.
You will need to have a base-case, for instance, if (num === 0)
. then another logic to call the function recursively until the base-case condition is met.
function factorial(num) {
if (num < 0) {
console.log("Number must be greater than or equal to 0");
} else if (num === 0) {
return 1;
} else {
return num * factorial(num - 1);
}
}