Login

Factorial

Write a function that computes the factorial of a given number.

Advanced


Instructions

Write a function that receives a number, computes and return its factorial.

For example, if the input is 5, the output should be 120.

Tests
0/7
Function Call:
Expected:
factorial(0)
1
Run test

factorial(1)
1
Run test

factorial(5)
120
Run test

Hidden Test
?
Run test

Hidden Test
?
Run test

Hidden Test
?
Run test

Hidden Test
?
Run test

See Solution

Solution

const factorial = (val) => {
    if(val < 0) return null
    if(val === 0) return 1
    return val * factorial(val - 1)
}

Explanation

The operation is simple. We loop through the numbers from 1 to 100 and check if the number is divisible by 3, 5 or both. If it is divisible by 3, we print "Fizz", if it is divisible by 5, we print "Buzz" and if it is divisible by both 3 and 5, we print "FizzBuzz". If none of the conditions are met, we print the number itself.

Complexity Analysis

The time complexity for this algorithm is O(n) where n is the number of elements in the array.

Alternatives

const factorial = (val) => {
    if(val < 0) return null
    if(val === 0) return 1
    let result = 1
    for(let i = 1; i <= val; i++) {
        result *= i
    }
    return result
}
Any improvement idea? Share with us!