0

I was trying to solve a problem with recursion .The problem was like this

The multiplicative persistence of an integer, n, is the number of times you have to replace n with the product of its digits until n becomes a single digit integer.

So my code was like this

    function multiplicativePersistence(n) {
      if(n.toString().length==1) return 0

      let c=1

      function ismul(num) {
        console.log(num,c)
        if(num.length==1) return c
        let n=num.toString()
        let mul=1

        for(let i=0;i<n.length;i++) {
          mul=mul*parseInt(n[i])
        }

        if(mul.toString().length!=1) {
          c++
          return ismul(mul)
        }
      }

      return ismul(n)
    }

  console.log(multiplicativePersistence(6788))

the output i get is as

6788 1
2688 2
768 3
336 4
54 5
20 6
undefined

why i am getting undefined even though my value of c is correctly update i,e 6 and then i am just returning it

Pac0
  • 21,465
  • 8
  • 65
  • 74
Ratnabh kumar rai
  • 1,426
  • 4
  • 21
  • 48
  • 4
    `console.log()` has a return value of `undefined` Also the `return` statement in `ismul()` is within an `if` block, so if the condition is false, the return value of `ismul()` is `undefined`. – Patrick Roberts May 13 '20 at 21:16
  • To be a bit more precise, when run in a console, `console.log()` will show `undefined` after logging (see [Chrome/Firefox console.log always appends a line saying undefined](https://stackoverflow.com/q/14633968/215552)). If you are running `console.log(fn())` in a JavaScript file, it should not append `undefined`, except if `fn` returns `undefined`. – Heretic Monkey May 13 '20 at 21:45

1 Answers1

1

you have to deal with the case length = 1 and move c to an outer scope to get something

var c = 1
function multiplicativePersistence(n) {
    if(n.toString().length==1) return 0
    function ismul(num){
        if(num.length==1) return  c
        let n=num.toString()
        let mul=1
        for(let i=0;i<n.length;i++){
            mul=mul*parseInt(n[i])
        }
        if(mul.toString().length!=1){
        console.log(num,c)
            c++
            return ismul(mul)
        } else {
        console.log(num,c)
            c++
            return mul
        }
    }

    return ismul(n)
}

console.log(multiplicativePersistence(6788), c)
Tuckbros
  • 417
  • 3
  • 13