Finding persistence of number in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an 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.

For example −

If the number is −

1679583

Then,

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

Therefore, the output should be 3.

Example

Following is the code −

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));

Output

Following is the output in the console −

3
raja
Published on 16-Sep-2020 13:55:50
Advertisements