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
Calculating a number from its factorial in JavaScript
We are required to write a JavaScript function that takes in a number as the only argument.
The function should check whether there exists any number whose factorial is the number taken as input.
If there exists any such number, we should return that number otherwise we should return -1.
Problem Understanding
Given a number, we need to find if it's a factorial of some integer. For example, 720 is the factorial of 6 because 6! = 6 × 5 × 4 × 3 × 2 × 1 = 720.
If the input is:
const num = 720;
Then the output should be:
const output = 6;
Solution Approach
We'll start with 1! and keep multiplying by increasing numbers until we either find our target number or exceed it.
Example
Following is the code:
const num = 720;
const checkForFactorial = num => {
let prod = 1, count = 1;
while(prod <= num){
if(prod === num){
return count;
};
count++;
prod *= count;
};
return -1;
};
console.log(checkForFactorial(num));
console.log(checkForFactorial(6565));
Output
6 -1
How It Works
The algorithm works by:
- Starting with
prod = 1(representing 1!) andcount = 1 - In each iteration, checking if current product equals our target
- If not, incrementing count and multiplying prod by the new count
- Continuing until we find a match or exceed the target
Alternative Implementation
Here's a more readable version with better variable names:
const findFactorialBase = (target) => {
let factorial = 1;
let number = 1;
while (factorial <= target) {
if (factorial === target) {
return number;
}
number++;
factorial *= number;
}
return -1;
};
// Test cases
console.log(findFactorialBase(24)); // 4! = 24
console.log(findFactorialBase(120)); // 5! = 120
console.log(findFactorialBase(100)); // Not a factorial
4 5 -1
Conclusion
This solution efficiently finds if a number is a factorial by iteratively calculating factorials until finding a match or exceeding the target. The time complexity is O(?n) in the worst case.
