How many times can we sum number digits in JavaScript

We are required to write a JavaScript function that takes in a positive integer and returns its additive persistence.

The additive persistence of an integer, say n, is the number of times we have to replace the number with the sum of its digits until the number becomes a single digit integer.

Example Walkthrough

For example: If the number is:

1679583

Then we calculate:

1 + 6 + 7 + 9 + 5 + 8 + 3 = 39  // Pass 1
3 + 9 = 12                        // Pass 2  
1 + 2 = 3                         // Pass 3

Therefore, the additive persistence is 3 (it took 3 iterations to reach a single digit).

Implementation

Here's the complete solution using a helper function to sum digits:

const num = 1679583;

const sumDigit = (num, sum = 0) => {
    if (num) {
        return sumDigit(Math.floor(num / 10), sum + num % 10);
    }
    return sum;
};

const persistence = num => {
    num = Math.abs(num);
    let res = 0;
    while (num > 9) {
        num = sumDigit(num);
        res++;
    }
    return res;
};

console.log(persistence(num));
3

How It Works

The solution consists of two functions:

  • sumDigit(): A recursive function that extracts and sums all digits of a number using division and modulo operations.
  • persistence(): The main function that repeatedly calls sumDigit() until the result becomes a single digit, counting the iterations.

Alternative Approach Using String Conversion

Here's a simpler approach using string methods:

function additivePersistence(num) {
    num = Math.abs(num);
    let count = 0;
    
    while (num >= 10) {
        num = num.toString()
                 .split('')
                 .map(Number)
                 .reduce((sum, digit) => sum + digit, 0);
        count++;
    }
    
    return count;
}

console.log(additivePersistence(1679583));  // 3
console.log(additivePersistence(25));       // 1
console.log(additivePersistence(9));        // 0
3
1
0

Key Points

  • Numbers with single digits (0-9) have additive persistence of 0
  • The function handles negative numbers by using Math.abs()
  • The recursive approach is more memory-intensive but demonstrates functional programming
  • The string conversion approach is more readable and easier to understand

Conclusion

Additive persistence measures how many steps it takes to reduce a number to a single digit by repeatedly summing its digits. Both recursive and iterative approaches work effectively for this mathematical problem.

Updated on: 2026-03-15T23:19:00+05:30

180 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements