Coding problem · Easy · Basics

Factorial

Easy Algorithms & data structures

Return n! (n factorial), the product of all integers from 1 to n. By definition 0! = 1. 0 <= n <= 18.

Example 1

Input: n = 5
Output: 120

Example 2

Input: n = 0
Output: 1

Hints

Hint 1

Multiply a running product by every number from 2 to n.

Hint 2

Recursion also works: n! = n × (n − 1)!

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(1)

Iterate from 2 to n multiplying an accumulator that starts at 1. Factorials grow fast: 18! is about 6.4 × 10¹⁵, close to the largest integer JavaScript numbers represent exactly; Java uses long.

Reference solution

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

Was this page helpful?