-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem-9_Find_the_Factorial_of_a_Number.js
More file actions
37 lines (29 loc) · 1.39 KB
/
Problem-9_Find_the_Factorial_of_a_Number.js
File metadata and controls
37 lines (29 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Problem-9_Find_the_Factorial_of_a_Number with Solution, Explanation, Verification, and Execution:
// To find the factorial of a number, we can implement the Solution like below:
// -------------------------------------------------------------------
function factorial(n) {
if (n < 0) return null;
let result = 1;
for (let i = 1; i <= n; i++) {
result *= i;
}
return result;
}
// Explanation:
// ---------------
// The function first checks for negative input, returning null as factorial is undefined for negatives. It initializes the result to 1 (factorial of 0 or 1). A for loop multiplies the result by each integer from 1 to n inclusive. This iterative multiplication builds the factorial value progressively, using a loop instead of recursion for simplicity and efficiency.
// Verification:
// ----------------
// function factorial(n) {
// if (n < 0) return null;
// let result = 1;
// for (let i = 1; i <= n; i++) {
// result *= i;
// }
// return result;
// }
// console.log(factorial(5));
// Execution of the above code block in IDE environment with node.js installed:
// ----------------------------------------------------------------------
// Input (In the directory in IDE environment with node.js installed): 'node Problem-9_Find_the_Factorial_of_a_Number.js'
// Output (In the directory in IDE environment with node.js installed): "Hello World"