Recursive multiplication of the digits of an integer, how to find out the number of function calls?

  • 0
    Hello.
    The program must implement bitwise multiplication of a positive integer until 1 digit remains and return the number of steps to this result. Example:
    99999 = & gt; 59049 = & gt; 0 === 2 steps // 9 * 9 * 9 * 9 * 9 = & gt; 5 * 9 * 0 * 4 * 9 = & gt; 0;
    13 = & gt; 3 === 1 step // 1 * 3 = & gt; 3;
    999 = & gt; 729 = & gt; 126 = & gt; 12 = & gt; 2 === 4 steps // 9 * 9 * 9 = & gt; 7 * 2 * 9 = & gt; 1 * 2 * 6 = & gt; 1 * 2 = & gt; 2;
    7 = & gt; 7 === 0 steps //
    Is it possible to insert a function call counter into recursion?

    let steps = 0;
    function umnozhenie(x) {
        steps += 1;
        x = String(x).match(/[0-9]/g).map(Number).reduce((a, b) => a * b);
        if (x >= 10) { x = umnozhenie(x); };
        return steps;
    }


    The program shows incorrect results with large numbers. But if I put the function itself in return , then I get the correct value of the final digit.
    I can't work with a cycle.
    JavaScript Anonymous, Nov 1, 2019

  • 2 Answers
  • 0
    const multiply = num =>
    num > 9
    ? 1 + multiply([...`${num}`].reduce((acc, n) => acc * n))
    : 0;
    Scarlet Reed

  • 0
    If a person does not know how to work with loops, then he should not tackle recursion.

    Best of all in this case is the while (x & gt; 9) {...} loop. Inside the loop, you need to use the operations "mod 10" (the remainder of the division by ten - to get the last digit) and "div 10" (the rest of the number) - and so, extracting the digits in turn, multiply them.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!