Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Writing a For Loop to Evaluate a Factorial - JavaScript
We are required to write a simple JavaScript function that takes in a Number, say n and computes its factorial using a for loop and returns the factorial.
For example:
factorial(5) = 120, factorial(6) = 720
The approach is to maintain a count and a result variable, keep multiplying the count into result, simultaneously decreasing the count by 1, until it reaches 1. Then finally we return the result.
Syntax
function factorial(n) {
let result = 1;
for (let i = n; i > 1; i--) {
result *= i;
}
return result;
}
Example
Following is the code:
const num = 14;
const factorial = num => {
let res = 1;
for(let i = num; i > 1; i--){
res *= i;
}
return res;
};
console.log(factorial(num));
Output
This will produce the following output in console:
87178291200
How It Works
The factorial function works by:
- Starting with
res = 1(multiplicative identity) - Using a for loop that counts down from
numto2 - Multiplying each number into the result:
res *= i - Returning the final accumulated product
Additional Examples
// Test with smaller numbers console.log(factorial(5)); // 5! = 5 × 4 × 3 × 2 × 1 console.log(factorial(6)); // 6! = 6 × 5 × 4 × 3 × 2 × 1 console.log(factorial(0)); // Edge case: 0! = 1 console.log(factorial(1)); // Edge case: 1! = 1
120 720 1 1
Conclusion
The for loop approach provides an efficient iterative solution for calculating factorials. It avoids recursion overhead and works well for reasonable input sizes.
Advertisements
