Home > Mobile >  Multiplicative persistence using recursion
Multiplicative persistence using recursion

Time:09-21

I was trying to make a function that calculates the multiplicative persistence on my own. It works when I pass in a number that has a multiplicative persistence value of 2 or less.

But when passing in a number whose multiplicative persistence is more than 2, it is returning an incorrect value.

Here is the function I wrote:

function persistence(num) {
  let res = 10
  let count=0
  const helper = (number)=>{
    res=1
    const digits = number.toString().split('')
    for(let digit of digits){
      res = res* Number(digit)
    }
    count  
    console.log(res,count)
    return
  }
  if(num<10) return 0
  if(res>=10){
    if(count===0) helper(num)
    helper(res)
  }
  return count
}

CodePudding user response:

You can implement the digit multiplication by using a reduce; then it is simply a matter of returning either 0 if num < 10 or 1 persistence(prod) if num > 10:

const persistence = (num) => {
  if (num < 10) return 0
  const prod = num.toString().split('').reduce((acc, d) => acc * d, 1)
  return 1   persistence(prod)
}

console.log(persistence(5))
console.log(persistence(437))
console.log(persistence(1379))

  • Related