Introduction
The factorial of a number is the product of all positive integers less than or equal to that number. It is denoted as n!
. For example, the factorial of 5
is 5! = 5 * 4 * 3 * 2 * 1 = 120
. Factorials are used in many areas of mathematics, especially in combinatorics, algebra, and calculus. This program helps calculate the factorial of a given number in JavaScript.
Problem Statement
Create a JavaScript program that:
- Accepts a positive integer.
- Calculates and returns the factorial of that number.
Example:
Input:
5
Output:
120
Input:
3
Output:
6
Solution Steps
- Read the Input Number: Provide the number either as user input or directly within the code.
- Handle Edge Case: If the input number is
0
, return1
as0! = 1
. - Calculate the Factorial: Use either an iterative loop or recursion to calculate the factorial.
- Display the Result: Print the calculated factorial.
JavaScript Program
// JavaScript Program to Find the Factorial of a Number
// Author: https://www.javaguides.net/
function factorial(n) {
// Step 1: Handle base case
if (n === 0 || n === 1) {
return 1;
}
// Step 2: Calculate the factorial iteratively
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
// Example input
let inputNumber = 5;
let result = factorial(inputNumber);
console.log(`The factorial of ${inputNumber} is: ${result}`);
Output
The factorial of 5 is: 120
Example with Different Input
let inputNumber = 3;
let result = factorial(inputNumber);
console.log(`The factorial of ${inputNumber} is: ${result}`);
Output:
The factorial of 3 is: 6
Explanation
Step 1: Handle the Base Case
- If the number is
0
or1
, the factorial is defined as1
, so the program returns1
immediately for these values.
Step 2: Calculate the Factorial Iteratively
- For numbers greater than
1
, the function uses afor
loop to calculate the factorial by multiplying the result variable with each number from2
ton
.
Step 3: Display the Result
- The calculated factorial is printed using
console.log()
.
Conclusion
This JavaScript program demonstrates how to calculate the factorial of a given number using an iterative approach. Factorials are a fundamental mathematical concept, and this program provides a simple and efficient way to compute them in JavaScript. You can modify this solution to use recursion or handle larger inputs if needed.
Comments
Post a Comment
Leave Comment