javascriptarraysloopsmath

Persistent Bugger - Help to get rid of some 0


I need some help with a task which is about creating a function that only accepts integer numbers to then multiply each other until getting only one digit. The answer would be the times:

Example: function(39) - answer: 3 Because 3 * 9 = 27, 2 * 7 = 14, 1 * 4 = 4 and 4 has only one digit

Example2: function(999) - answer: 4 Because 9 * 9 * 9 = 729, 7 * 2 * 9 = 126, 1 * 2 * 6 = 12, and finally 1 * 2 = 2

Example3: function(4) - answer: 0 Because it has one digit already

So trying to figure out how to solve this after many failures, I ended up coding this:

function persistence(num) {
   
  let div = parseInt(num.toString().split(""));
  let t = 0;
  
  if(Number.isInteger(num) == true){
    
    if(div.length > 1){
      
      for(let i=0; i<div.length; i++){
        
        div = div.reduce((acc,number) => acc * number);
        t += 1;
        div = parseInt(div.toString().split(""))
        
        if(div.length == 1){ 
          return t } else {continue}
        
      } return t
              
    } else { return t }
       
  } else { return false }
  
  }

console.log(persistence(39),3);
console.log(persistence(4),0);
console.log(persistence(25),2);
console.log(persistence(999),4);

/*
output: 0 3
        0 0
        0 2
        0 4
*/
  

It seems I could solve it, but the problem is I don't know why those 0s show up. Besides I'd like to receive some feedback and if it's possible to improve those codes or show another way to solve it.

Thanks for taking your time to read this.

///EDIT///

Thank you all for helping and teaching me new things, I could solve this problem with the following code:

function persistence(num){
  let t = 0;
  let div;

  if(Number.isInteger(num) == true){

    while(num >= 10){

      div = (num + "").split("");
      num = div.reduce((acc,val) => acc * val);
      t+=1;

    } return t

  }
}

console.log(persistence(39));
console.log(persistence(4));
console.log(persistence(25));
console.log(persistence(999));

/*output: 3
          0
          2
          4
*/

Solution

  • function persistance (num) {
        if (typeof num != 'number') throw 'isnt a number'
      let persist = 0
      while(num >= 10) {
        let size = '' + num
        size = size.length
        // Get all number of num
        const array = new Array(size).fill(0).map((x, i) => {
            const a = num / Math.pow(10, i)
          const b = parseInt(a, 10)
          return b % 10
        })
        console.log('here', array)
        // actualiser num
        num = array.reduce((acc, current) => acc * current, 1)
        persist++
      }
      return persist
    }
    console.log(persistance(39))
    console.log(persistance(999))