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
Finding persistence of number in JavaScript
The additive persistence of a number is the count of times you must repeatedly sum its digits until you get a single digit. This is a common programming problem that demonstrates recursion and digit manipulation.
Understanding Additive Persistence
For any positive integer, we replace it with the sum of its digits repeatedly until we reach a single digit (0-9). The number of iterations required is the additive persistence.
For example, with 1679583:
1679583 ? 1+6+7+9+5+8+3 = 39 (Pass 1) 39 ? 3+9 = 12 (Pass 2) 12 ? 1+2 = 3 (Pass 3)
Since it took 3 passes to reach a single digit, the additive persistence is 3.
Implementation
const num = 1679583;
// Helper function to sum digits of a number
const sumDigits = (num, sum = 0) => {
if (num) {
return sumDigits(Math.floor(num / 10), sum + num % 10);
}
return sum;
};
// Main function to find additive persistence
const persistence = num => {
num = Math.abs(num);
let count = 0;
while (num > 9) {
num = sumDigits(num);
count++;
}
return count;
};
console.log(persistence(num));
3
How It Works
The sumDigits function uses recursion to extract each digit using modulo (%) and integer division. The persistence function counts iterations until the number becomes single-digit.
Alternative Approach
const persistenceSimple = num => {
num = Math.abs(num);
let count = 0;
while (num >= 10) {
// Convert to string, split digits, sum them
num = num.toString().split('').reduce((sum, digit) => sum + parseInt(digit), 0);
count++;
}
return count;
};
// Test with different numbers
console.log(persistenceSimple(39)); // 2 passes: 39 ? 12 ? 3
console.log(persistenceSimple(999)); // 4 passes: 999 ? 27 ? 9
console.log(persistenceSimple(4)); // 0 passes: already single digit
2 4 0
Key Points
- Single-digit numbers (0-9) have persistence 0
- The function handles negative numbers by using
Math.abs() - Recursion provides an elegant digit-summing solution
- String manipulation offers a more readable alternative
Conclusion
Additive persistence demonstrates practical applications of digit manipulation and recursion. Both recursive and iterative approaches work effectively, with the choice depending on readability preferences.
