0

I want to write a factorial function in javascript. I have tried the following:

function factorial(n){
  if(n==1){
    return 1;
  } else {
   while(n>=0){
    n = n * (n-1);
   }
   return n;
 }
}

It is not working.

8 Answers8

2

First return 1 for number 0 and 1 input number. If number is greater than 1 then iterate from 2 to input number and multiple result * i; store into result variable.

function factorial(number) {
  let result = 1;

  for (let i = 2; i <= number; i++) {
    result = result * i;
  }

  return result;
}
Sagar
  • 4,473
  • 3
  • 32
  • 37
  • Why use let instead of var? –  Jul 16 '18 at 00:58
  • 1
    let is block scoped and var is function scoped read more here https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable-in-jav – Sagar Jul 16 '18 at 08:49
2

We can do it in the following way:

const factorial = (num: number): number => (num === 0) ? 1 : (num * factorial(num - 1));
H S W
  • 6,310
  • 4
  • 25
  • 36
1

You used while(n>=0) instead of while(n>=2). Using n>=0 will make the end of the while loop multiply n by 0. You should also use the === operator to prevent values that are not numeric. You also forgot to decrease n in the while loop. Try one of the following:

Iteration method:

function factorial(n){
 var result = n;
 if(n<0){
   return null;
 }
 if(n===1||n===0){
return 1;
 } else {
 while(n>=2){
 result = result * (n-1); 
 n--;
}
return result;
}
}

<script>
 function factorial(n){
     var result = n;
     if(n<0){
       return null;
     }
     if(n===1||n===0){
    return 1;
     } else {
     while(n>=2){
     result = result * (n-1); 
     n--;
    }
    return result;
    }
    }
function calculate(){
   var input = document.getElementById("number").value;
   if(!isNaN(input)&&input.trim().length){
    document.getElementById("result").innerHTML = factorial(parseInt(input, 10));
   } else {
    document.getElementById("result").innerHTML = "<b style='color: red;'>Input must be a number!</b>";
   }
}
</script>
<input type="text" id="number" onkeyup="calculate()">
<br/>
<span id="result"></span>

Recursive method:

function factorial(n){
 if(n===0||n===1){
   return 1;
 }
 return n*factorial(n-1);
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

Here is one I wrote after learning about the array function reduce()

const factorial = n => {
  if (! Number.isInteger(n)) return undefined
  if (n < 0) return undefined
  if (n === 0) return 1

  const array1 = [...Array(n+1).keys()].splice(1)

  return array1.reduce((preVal, curVal) => preVal * curVal)
}
0

Just adding a bit in H S Progr's answer as I did today this exercise. In Wikipedia says that 0! = 1 and 1! = 1 , so just an extra " making sure of"

const factorial = (n) => (num === 0 || num === 1) ? 1 : (num * factorial(num - 1));

As I said, I have no merit, as I am learning, but any possible way to ensure that in our if, else if, while ... or any other meaning we choose to do a factorial, we place 0 and 1 with their own unique value.
All merit in my answer ( that was closed to H R Progr, should go to Sonya Moisset who's brilliant article gave me the hints to follow.
This was my original code after reading her article:

const factorial = (n) => (n < 0) ? 1 : (n == 0) ? 1 : (n * factorial(n - 1));
0

so the below code works this way. the const gets the part of the html doc you want to print to. the prompt receives the number for testing. The fun begins with factorial calculation loop. the loop goes through and continues to multiply the number by its factorial. if you put in 8 the loop would return 40320 after it does all its pass throughs.

const html = document.getElementById('root');

// get number
let num1;
do {
    num1 = +prompt("enter number");
}
while (num1 <= 0);

//// factorial calculation using loop

let j = 1;
for (let i = 1; i <= num1; i++) {
    j = j * i;

    //show results on the screen

    html.innerHTML = `
    <p> ${j}</p>
    `;
}
Peter May
  • 31
  • 5
  • 1
    Welcome to SO! Could you please consider writing some explanation rather than just dumping a bunch of code in the answer. Good answers are supposed to provide insight to the problem rather than just provide a blind solution. Consider reading the guide at https://stackoverflow.com/help/answering. Good luck! – mandulaj Jan 15 '21 at 09:54
0
    let myArray = [];

    function calculateFactorial (myFacNumber)
    {
      
       let result = 1;
       let c; 
    
      for(let x = 1; x<=myFacNumber; x++)
      {
         for(let j = x; j<=x;j++)
         {
           c= myArray[j] = x;
           result *= c;
         }
      }
     return result; 
    }
    console.log(calculateFactorial(5));
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 07 '21 at 19:15
0

For future readers, I suggest a non-recursive version of this function.

function factorial(n){
    if(n < 0 || !Number.isInteger(n)){
         throw Error(`Can't compute factorial(${n}) as factorial is defined for positive integers`);
    }

    let r = 1;
    for(let k=1; k<n+1; k++){
        r *= k;
    }
    return r;
}

Since the function is defined only for positive integers, I have a preference to validate its input to avoid weird errors if n is undefined or not an integer for example.

Sylvan LE DEUNFF
  • 682
  • 1
  • 6
  • 21