简体   繁体   中英

How to calculate the factorial of a number entered by user in Javascript, using, do-loop, while-loop?

Quick follow-up question on my previous question. I'd like to add the code to the following to calculate the factorial of a number entered by user in Javascript.

<!DOCTYPE html>
<html>
<head>
<title>Sum of Numbers</title>
 <script>
  var numbers = prompt("Enter a  number 1-100");

  while (numbers!=null && (isNaN(parseInt(numbers)) || parseInt(numbers) >100 || parseInt(numbers) <1)) {
      numbers = prompt("Try again.Enter a  number 1-100");
  }
  

  if (numbers !=null){
        alert("Finally you entered a correct number");

  var sum = 0;
  var numOfLoops = numbers;
  var counter = 1;
  do {
    sum+=counter;
    counter++;
  }

  while (counter<=numOfLoops)
  alert ("The sum of numbers from 1 to " + numbers + "is =" +sum);
}
 </script>

</head>
<body>
    <script>
    document.write("<h1>Sum of Numbers</h1>");
        document.write("The sum of numbers from 1 to = " + numbers +  "&nbsp;is = "  +
            + sum + "<br><br>");
    </script>

</body>
</html>

If you are trying to sum up the numbers, consider using arithmetic series formula. If you're trying to get the factorial, the approach is shown below.

If you want to sum using the loop, just change the *= to += .

While Loop Approach

const fact = (n) => {
  
let res = 1;
  
while (n > 0) {
  res *= n;
  n--;
}
  
return res;
  
}

fact(5) // 120

Do While Approach

const fact = (n) => {
  
  let res = 1;
  
  do {
    res *= n;
    n--;
  } while (n > 0)
  
  return res;
  
}

fact(3) // 6

That should do the trick. :)

Maybe also considering checking for edge cases like if the n is negative.

Good luck.

While Loop:

const fact=n=>
  {
  if(n<0) throw 'factorial error on a negative number!'
  let r = 1
  while(n) r *= n--
  return r
  }

Do While:

const fact=n=>
  {
  if(n<0) throw 'factorial error on a negative number!'
  let r = 1
  do  r *= n || 1 // in case of n == 0
  while (n--)
  return r;
  }

complete code

 const msgPrompt_1 = 'Please enter a number from 0 to 100', msgPrompt_n = 'Try again.... Enter a number 0-100', fact = n => { let r = 1 while(n) r *= n-- return r } let numValue = parseInt(window.prompt(msgPrompt_1, ''), 10) while(isNaN(numValue) || numValue > 100 || numValue < 0) { numValue = parseInt(window.prompt(msgPrompt_n, ''), 10) } alert(`factorial value of ${numValue} is = ${fact(numValue)}` )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM