Foundations Recursion basics

39. Factorial of N

Easy

The factorial of a whole number n, written n!, is the product of every whole number from 1 to n:

n! = 1 × 2 × 3 × … × n

So 4! = 1 × 2 × 3 × 4 = 24. The factorial of 0 is 1: a product of no numbers is 1, in the same way that a sum of no numbers is 0.

Given n, return n!.

Example 1

Input: n = 5

Output: 120

Explanation: 5! = 1 × 2 × 3 × 4 × 5 = 120.

Example 2

Input: n = 0

Output: 1

Explanation: 0! is 1.

Example 3

Input: n = 20

Output: 2432902008176640000

Check your understanding

Work out the answer for this input before you write any code.

n = 4

Constraints

  • 0 ≤ n ≤ 20

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.