Editor

Factorial

#20 · Loops · Intermediate · 65 XP · about 6 min

Write a function called factorial(n) that calculates the factorial of a non-negative integer n.

The factorial of n (written as n!) is the product of all positive integers from 1 to n: - 5! = 5 × 4 × 3 × 2 × 1 = 120 - 0! = 1 (by definition)

Example

factorial(5)   # Returns 120
factorial(0)   # Returns 1
factorial(1)   # Returns 1
factorial(10)  # Returns 3628800

Requirements

  • Handle n = 0 (returns 1)
  • You can assume n is non-negative
  • Use a loop (not recursion)

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.