Implement the method factorial that takes a non-negative integer as input and returns its factorial.

Learner Level
Loop Math

You need to write a function that calculates the factorial of a non-negative number.

The factorial of a number means multiplying that number by every whole number less than it down to 1.

For example:

  • factorial(5) means → 5 × 4 × 3 × 2 × 1 = 120
  • factorial(3) means → 3 × 2 × 1 = 6

By definition:

  • The factorial of 0 is 1
  • The factorial of 1 is also 1

Your task is to implement this logic and return the result.

Example 1
Input:
n (int) = 0
Return:
(int) 1
Example 2
Input:
n (int) = 1
Return:
(int) 1
Example 3
Input:
n (int) = 3
Return:
(int) 6
Example 4
Input:
n (int) = 5
Return:
(int) 120
Example 5
Input:
n (int) = 10
Return:
(int) 3628800

To compute the factorial of a number:

  1. Initialize a result variable to 1
    The factorial of 0 or 1 is 1, so we start with result = 1.

  2. Iterate from 2 up to n
    Multiply the result by each number from 2 to n.

  3. Return the result
    After the loop ends, return the result as the factorial value.

Pseudocode:

Function factorial(n):
    result ← 1
    For i from 2 to n:
        result ← result × i
    Return result
Run your code to see the result.