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;
}
function factorial(n: number): number {
let result = 1;
for (let i = 2; i <= n; i++) result *= i;
return result;
}
def factorial(n: int) -> int:
result = 1
for i in range(2, n + 1):
result *= i
return result
<?php
function factorial(int $n): int
{
$result = 1;
for ($i = 2; $i <= $n; $i++) {
$result *= $i;
}
return $result;
}
class Solution {
public long factorial(int n) {
long result = 1;
for (int i = 2; i <= n; i++) result *= i;
return result;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy