Easy 0 solved 0% acceptance

Factorial

Multiply all positive integers up to n.

What you'll learn

  • Multiply a sequence of numbers with a loop
  • Start a product at 1 instead of 0
  • See how quickly factorials grow

Problem

The factorial of n, written n!, is 1 × 2 × … × n. By definition 0! = 1.

Implement factorial(n).

Input

n: A non-negative integer.

Output

Return n!.

Constraints

0 ≤ n ≤ 20, so the result fits a signed 64-bit integer.

Examples

Example 1
Input:
n = 5

Expected output:
expected = 120
Input:
long long n = 5;

Expected output:
long long expected = 120;
Input:
long n = 5;

Expected output:
long expected = 120;

Explanation

1 × 2 × 3 × 4 × 5 = 120.

Example 2
Input:
n = 0

Expected output:
expected = 1
Input:
long long n = 0;

Expected output:
long long expected = 1;
Input:
long n = 0;

Expected output:
long expected = 1;

Explanation

0! is defined as 1.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Factorial multiplies all integers from 1 up to the given number.

Hint 2

An iterative running product is enough, and 0 has a special defined result.

Hint 3

Because the input is small, overflow is the main detail to watch for in other languages.

Expected complexity

O(n) time, O(1) extra space

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.