How to find the factorial of 10 in javascript

PHPz
Release: 2023-04-24 14:21:47
Original
933 people have browsed it

In JavaScript, you can solve for the factorial of 10 using a loop or recursion.

  1. Loop to solve the factorial of 10

The code to loop to solve the factorial of 10 is as follows:

function factorial(num) {
  var result = 1;
  for (var i = 2; i <= num; i++) {
    result *= i;
  }
  return result;
}

console.log(factorial(10));  // 3628800
Copy after login

A function is defined herefactorial, accepts a parameter num, indicating the factorial number to be solved. A variable result is defined in the function, with an initial value of 1. Then use the for loop to traverse from 2 to num, multiply i and result each time, and update result value. Finally returns result.

  1. Recursively solve the factorial of 10

The code to recursively solve the factorial of 10 is as follows:

function factorial(num) {
  if (num <= 1) {
    return 1;
  } else {
    return num * factorial(num - 1);
  }
}

console.log(factorial(10));  // 3628800
Copy after login

also defines a functionfactorial, accepts a parameter num, indicating the factorial number to be solved. A recursive call to itself is used inside the function to calculate the factorial. When num is less than or equal to 1, the return value is 1; otherwise, the value of num multiplied by factorial(num - 1) is returned. In this way, when the recursion reaches num equals 1, all recursive calls will end and return 1, and the final value is the factorial of 10.

Summary

The above are two ways to solve the factorial of 10 in JavaScript, which are loop and recursion. Loop code is relatively simple and intuitive, while recursive code is more elegant, but problems may arise due to stack overflow when solving factorials of large numbers. Therefore, in actual use, it is necessary to choose an appropriate algorithm according to the actual situation.

The above is the detailed content of How to find the factorial of 10 in javascript. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template