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
Repeated sum of Number's digits in JavaScript
We are required to write a JavaScript function that recursively sums up the digits of a number until it reduces to a single digit number.
We are required to do so without converting the number to String or any other data type.
How It Works
The algorithm uses two functions:
- sumDigit(): Recursively extracts and sums all digits of a number
- sumRepeatedly(): Repeatedly calls sumDigit() until result is a single digit
Example
Let's implement the solution step by step:
const num = 546767643;
const sumDigit = (num, sum = 0) => {
if(num){
return sumDigit(Math.floor(num / 10), sum + (num % 10));
}
return sum;
};
const sumRepeatedly = num => {
while(num > 9){
num = sumDigit(num);
};
return num;
};
console.log("Original number:", num);
console.log("Final result:", sumRepeatedly(num));
Original number: 546767643 Final result: 3
Step-by-Step Breakdown
Let's trace how 546767643 reduces to 3:
const traceReduction = (num) => {
console.log("Starting with:", num);
while(num > 9) {
const digitSum = sumDigit(num);
console.log(`Sum of digits: ${digitSum}`);
num = digitSum;
}
console.log("Final single digit:", num);
return num;
};
const sumDigit = (num, sum = 0) => {
if(num){
return sumDigit(Math.floor(num / 10), sum + (num % 10));
}
return sum;
};
traceReduction(546767643);
Starting with: 546767643 Sum of digits: 57 Sum of digits: 12 Sum of digits: 3 Final single digit: 3
Alternative Approach Using Math Only
Here's a more direct mathematical approach:
const digitalRoot = (num) => {
// Handle zero case
if (num === 0) return 0;
// Mathematical formula for digital root
return 1 + (num - 1) % 9;
};
console.log("Using formula - 546767643:", digitalRoot(546767643));
console.log("Using formula - 999:", digitalRoot(999));
console.log("Using formula - 12:", digitalRoot(12));
Using formula - 546767643: 3 Using formula - 999: 9 Using formula - 12: 3
Comparison
| Method | Time Complexity | Approach |
|---|---|---|
| Recursive Sum | O(log n × d) | Repeatedly sum digits until single digit |
| Mathematical Formula | O(1) | Direct calculation using modulo |
Conclusion
Both approaches solve the repeated digit sum problem without string conversion. The recursive method shows the step-by-step process, while the mathematical formula provides instant results using the digital root property.
Advertisements
