Solution to the clumsy factorial problem in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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.

Let's write the code for this function in JavaScript −

Example

const clumsy = num => {
   let k=num;
   let res = 0, temp=1, i=0;
   while(k>0){
      temp = k;
      if(k-1>0){
         temp*=(k-1);
      }
      if(k-2>0){
         temp/=(k-2);
      }
      if(k-3>0){
         if(k===num){
            temp+=(k-3);
         }else{
            temp-=(k-3);
         }
      }
      if(k===num){
         res = temp;
      }else{
         res = res-temp;
      }
      k = k-4;
   }
   return res;
};
console.log(clumsy(4));
console.log(clumsy(10));
console.log(clumsy(16));
console.log(clumsy(5));

Output

The output in the console will be −

7
11.75
16.609523809523807
7.666666666666668
raja
Published on 31-Aug-2020 06:39:21
Advertisements