Joe Astuccio

Joe Astuccio

Finding Multiplicative Persistence with JavaScript

11/04/20191 Min Read — In algorithms, javascript

Persistent Bugger is a fun little coding challenge from Codewars.

SPOILERS AHEAD. If you want to try to solve this algorithm yourself stop reading and click the link above.

Multiplicative persistence are big words that mean the number of times you must multiply the digits in a number until you reach a single digit.

examples:

persistence(39) should return 3 times

  • (1) 3x9 = 27
  • (2) 2x7 = 14
  • (3) 1x4 = 4 ( and 4 has only one digit )

persistence(999) should return 4 times

  • (1) 9x9x9 = 729
  • (2) 7x2x9 = 126
  • (3) 1x2x6 = 12
  • (4) 1x2 = 2

persistence(4) === 0 times

  • 4 is already a one-digit number

There was a lot of confusion in the comments if calling persistence(999) should equal 4 or 2 (the number it finally reduces to) I was confused too until my friend Safiy shared his correct solution.

I was frustrated at first because I misunderstood what the Codewars tests were asking for. This caused me to search for solutions and learn to use the devtools debugger to step through code.

This is my refactored solution.

1const persistence = (num, times = 0) => {
2 while (num > 9) {
3 times++;
4 num = num
5 .toString()
6 .split('')
7 .reduce((a, b) => a * b);
8 }
9
10 return times;
11};

On line 1 we set the default value of times to 1. If num is 9 or less, already a single digit, the while loop starting on line 3 does not run. times is returned (line 8) ending the function

When num is greater 9:

  • times is incremented on line 4
  • num is converted toString() and then an array using split('')
  • reduce() multiplies all the numbers in the array until the result is 9 or less.