Difference between product and sum of digits of a number in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in an positive integer as the only argument.

The function should first count the sum of the digits of the number and then their product. Finally, the function should return the absolute difference of the product and the sum.

For example −

If the input number is −

const num = 12345;

Then the output should be −

const output = 105;

Example

Following is the code −

const num = 12345;
const product = (num, res = 1) => {
   if(num){
      return product(Math.floor(num / 10), res * (num % 10));
   }
   return res;
};
const sum = (num, res = 0) => {
   if(num){
      return sum(Math.floor(num / 10), res + (num % 10));
   }
   return res;
};
const productSumDifference = (num = 1) => {
   return Math.abs(product(num) - sum(num));
};
console.log(productSumDifference(num));

Output

Following is the console output −

105
raja
Published on 20-Jan-2021 06:58:47
Advertisements