I want to make a function that multiplies the digits of a number until they give a result less than 10 and returns the number of multiplications of the digits of the number passed by parameter that were made...
Ex: function(234) = 2 // because 2*3*4 = 24, 2*4 = 8
Ex: function(49) = 3 // because 4*9 = 36, 3*6 = 18, 1*8=8
function multiplicacionPersistente(num) {
let multiplicacion = String(num).split('').map(numeros => (
Number(numeros)
)).reduce((anterior,actual) =>(
anterior*actual
));
return multiplicacion
}
var respuesta = multiplicacionPersistente(999)
console.log(respuesta);
It would be something like doing this function of mine but many times... recursive... thanks
You have the base case: the number is less than 10 (one digit):
The case to iterate over would be when n > 10:
all this gives:
A solution without using recursion could be the following:
let counter = 0
).As long as the number is greater than or equal to 10:
eg: ''+num ==> string
)eg: string.split('') ==> array
)eg: array.reduce((acc, n) => acc * n) ==> number
)eg: counter++
).Example:
A simple way to make your function recursive would be like this:
Well, believe it or not, there is an even simpler method with fewer lines, using a
for
:This is the most optimal way possible, greetings.