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
Selected Reading
Recursive product of summed digits JavaScript
We need to create a function that takes multiple numbers as arguments, adds them together, then repeatedly multiplies the digits of the result until we get a single digit.
Problem Breakdown
For example, with arguments 16, 34, 42:
16 + 34 + 42 = 92
Then multiply digits until single digit:
9 × 2 = 18 1 × 8 = 8 (final result)
Solution Approach
We'll break this into two helper functions:
produce()- calculates the product of digits in a number using recursionadd()- sums all the input arguments
Complete Implementation
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));
6 5 2
How It Works
Let's trace through the first example (16, 28):
// Step 1: Add numbers
console.log("Step 1: 16 + 28 =", 16 + 28);
// Step 2: Multiply digits of 44
console.log("Step 2: 4 × 4 =", 4 * 4);
// Result is 16, which is > 9, so repeat
console.log("Step 3: 1 × 6 =", 1 * 6);
// Final result: 6
Step 1: 16 + 28 = 44 Step 2: 4 × 4 = 16 Step 3: 1 × 6 = 6
Breaking Down the Helper Functions
The produce() function uses recursion to multiply digits:
const produce = (n, p = 1) => {
console.log(`Processing: ${n}, current product: ${p}`);
if (n) {
const digit = n % 10;
const remaining = Math.floor(n / 10);
console.log(`Digit: ${digit}, Remaining: ${remaining}`);
return produce(remaining, p * digit);
}
return p;
};
// Example with number 123
console.log("Final product:", produce(123));
Processing: 123, current product: 1 Digit: 3, Remaining: 12 Processing: 12, current product: 3 Digit: 2, Remaining: 1 Processing: 1, current product: 6 Digit: 1, Remaining: 0 Processing: 0, current product: 6 Final product: 6
Conclusion
This recursive solution efficiently handles the digit multiplication process by breaking the number down digit by digit and accumulating their product until a single digit remains.
Advertisements
