Calculating a number from its factorial in JavaScript

JavascriptWeb DevelopmentFront End Technology

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.

For example −

If the input is −

const num = 720;

Then the output should be −

const output = 6;

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

Following is the console output −

6
-1
raja
Published on 22-Jan-2021 06:59:55
Advertisements