DEV Community

Pranava S Balugari
Pranava S Balugari

Posted on

Clumsy Factorial

One of the interesting Leet code problems i solved in recent times.

Normally, the factorial of a positive integer n is the product of all positive integers less than or equal to n. For example, factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1.

We instead make a clumsy factorial: using the integers in decreasing order, we swap out the multiply operations for a fixed rotation of operations: multiply (*), divide (/), add (+) and subtract (-) in this order.

For example, clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1. However, these operations are still applied using the usual order of operations of arithmetic: we do all multiplication and division steps before any addition or subtraction steps, and multiplication and division steps are processed left to right.

Additionally, the division that we use is floor division such that 10 * 9 / 8 equals 11. This guarantees the result is an integer.

Implement the clumsy function as defined above: given an integer N, it returns the clumsy factorial of N.


/**
 * @param {number} N
 * @return {number}
 */
var clumsy = function(N) {
    let operators = ['*', '/', '+', '-']
    let index = 0
    let stack = []

    // Add an element to the top of the stack.
    // Initially i created a result variable and 
    // was performing the operations in the case: block
    // But the problem with that is that it was not following
    // BODMOS mathematical principle. 
    // Goal is to ensure Multiplications and Divisions happen
    // Before additions and subtractions in the order.
    // After formulating an array, just add all those elements
    // to get the total Sum :)
    stack.push(N)

    for(let i = N - 1 ; i >=1; i--){
        /*
            Our goal is to push the evaluated values ontop
            Multiplication and division: Evaluate
            Addition and Subtraction: append
        */
        switch(operators[index]){
            case '*':
                len = stack.length - 1
                if(stack[len] >= 0){
                     stack[len] = stack[len] * i
                }else{
                    stack[len] = stack[len] * i
                }
                break;
            case '/':
                len = stack.length - 1
                 if(stack[len] >= 0){
                     stack[len] = Math.floor(stack[len] / i)
                }else{
                    stack[len] = -1 * Math.floor(Math.abs(stack[len]) / i)
                }
                break;
            case '+':
                stack.push(i)
                break;
            case '-':
                stack.push(-1 * i)
                break;
        }

        index = (index + 1) % operators.length
    }

    // Sum all the elements in the stack
    return stack.reduce((acc,element) => {
        acc = acc + element
        return acc
    })
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)