Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between product and sum of digits of a number in JavaScript
We are required to write a JavaScript function that takes in a positive integer as the only argument.
The function should first calculate the sum of the digits of the number and then their product. Finally, the function should return the absolute difference between the product and the sum.
For example, if the input number is 12345:
- Sum of digits: 1 + 2 + 3 + 4 + 5 = 15
- Product of digits: 1 × 2 × 3 × 4 × 5 = 120
- Absolute difference: |120 - 15| = 105
Example
Following is the complete implementation:
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
105
How It Works
The solution uses two recursive helper functions:
- product(): Calculates the product of digits by multiplying the last digit with the result of remaining digits
- sum(): Calculates the sum of digits by adding the last digit to the sum of remaining digits
Both functions use num % 10 to extract the last digit and Math.floor(num / 10) to remove it for the next recursive call.
Alternative Iterative Approach
Here's a simpler iterative solution:
function productSumDifference(num) {
let sum = 0;
let product = 1;
while (num > 0) {
let digit = num % 10;
sum += digit;
product *= digit;
num = Math.floor(num / 10);
}
return Math.abs(product - sum);
}
console.log(productSumDifference(12345));
console.log(productSumDifference(234));
105 14
Conclusion
Both recursive and iterative approaches effectively calculate the difference between product and sum of digits. The iterative version is generally more efficient and easier to understand.
