Factorial are the product of an integer and all the integers below it
eg: 2! = 2 * 1 = 2
Simple isnt it!
Now lets see how it work in our Javascript
Take a look at code below
//we created a function
function factorial(num) {
// initializing
var factorial = 1;
//using for loop we multiplied until num
for (var i = 1; i <= num; i++) {
// multiply each number between 1 and num
// factorial = 1 * 1 = 1
// factorial = 1 * 2 = 2
// factorial = 2 * 3 = 6
// factorial = 6 * 4 = 24
// ...
factorial = factorial * i;
}
console.log(factorial);
}
// keep this function call here
factorial(4);
output:
4*3*2*1 = 24
24
Got it! Right
BUT you might wonder what is practical use of it ..like in real life ..mmmmm good question
In real life we use it to find the no of outcomes ..like probability
Lets take an example:
do you love ice cream? i love a lot so we will use ice cream example..
Suppose you want 3 flavor scoop of ice cream on your cone
you choosed:
- Chocolate
- Strawberry
- Vanilla
sounds sweets
Now which topping to put first or second or last on cone.....?
how many combination it will give so we use factorial
3 flavor so 3! > 3*2*1 = 6 combination
ie:
1. Chocolate-Strawberry-Vanilla
2. Chocolate-Vanilla-Strawberry
3. Strawberry-Vanilla-Chocolate
4. Strawberry-Chocolate-Vanilla
5. Vanilla-Strawberry-Chocolate
6. Vanilla-Chocolate-Strawberry
ahhh what a taste... now i am enjoying my ice cream
hope you have found this taste too :)
Top comments (0)