Learner Level

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

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
Returns (int) 1

Example 2

Input
n (int) = 1
Returns (int) 1

Example 3

Input
n (int) = 3
Returns (int) 6

Example 4

Input
n (int) = 5
Returns (int) 120

Example 5

Input
n (int) = 10
Returns (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
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.