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
is1
- The factorial of
1
is also1
Your task is to implement this logic and return the result.
To compute the factorial of a number:
-
Initialize a result variable to 1
The factorial of 0 or 1 is 1, so we start withresult = 1
. -
Iterate from 2 up to n
Multiply the result by each number from 2 to n. -
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