Recursive product of summed digits JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We have to create a function that takes in any number of arguments (Number literals), adds them together, and returns the product of digits when the answer is only 1 digit long.

For example −

If the arguments are −

16, 34, 42

We have to first add them together −

16+34+42 = 92

And then keep multiplying the digits together until we get a 1-digit number like this −

9*2 = 18
1*8 = 8

When we get the one-digit number, we have to return it from our function.

We will break this into two functions −

  • One function accepts a number and returns the product of its digits, we will use recursion to do so, let’s call this first function product().

  • Second function recursively calls this product() function and checks if the product happens to be 1 digit, it returns the product otherwise it keeps on iterating.

The code for this whole functionality will be −

Example

const recursiveMuliSum = (...numbers) => {
   const add = (a) => a.length === 1 ? a[0] : a.reduce((acc, val) => acc+val);
   const produce = (n, p = 1) => {
      if(n){
         return produce(Math.floor(n/10), p*(n%10));
      };
      return p;
   };
   const res = produce(add(numbers));
   if(res > 9){
      return recursiveMuliSum(res);
   }
   return res;
};
console.log(recursiveMuliSum(16, 28));
console.log(recursiveMuliSum(16, 28, 44, 76, 11));
console.log(recursiveMuliSum(1, 2, 4, 6, 8));

Output

The output in the console will be −

6
5
2
raja
Published on 24-Aug-2020 09:20:44
Advertisements