I have the following problem:

Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.

function persistence(num) {

  let count = 0; 
  let numStr = num.toString(); 

   if (numStr.length === 1){
     return 0
   } 

   if (numStr.length === 2){
     while (numStr.length > 1){
       count += 1
       numStr = (Number(numStr[0])*Number(numStr[1])).toString() 
     }
   }

   if (numStr.length === 3){
     while (numStr.length > 1){
       count += 1
       numStr = (Number(numStr[0])*Number(numStr[1])*Number(numStr[2])).toString() 
     }
   }

   return count 
}

persistence(999) //solution 4

I'm getting "Execution Timed Out (12000 ms)" error. I know there's different ways to tackle this problem but I want to know specifically what is wrong with my code.

2 Answers

1
Arthur On

With recursive function you can do it easily :

Just add a new args count (how many time this function as been called) and recall it while the result length is more than 1

function persistence(num, count) {
  count = count || 0; 
  let numStr = num.toString(); 
  
  if (numStr.length === 1) {
    return count
  } 
  let new_num = numStr.split('').reduce((acc, val) => {
    return acc * val
  }, 1)
  return persistence(new_num, count + 1) 
}

console.log("99", persistence(99))
console.log("999", persistence(999))
console.log("99999", persistence(99999))

2
Maheer Ali On

The reason your code is not working because you are always adding str[2] to the final result.

999 > 729 > 126 > 12 > 2

So here you see at one loop number becomes 12 and str[2] is undefined and it will be NaN so loop never ends.

A simple way is using reduce() inside while and no need to convert the to Number() while multiplying

function persistence(num) {

  let count = 0; 
  num = String(num);
  while(num.length > 1){
    count++;
    num = String([...num].reduce((ac,a) => a * ac,1));
  }
  return count;
}

console.log(persistence(999))