N
N
nataleya20102022-03-30 22:26:48
recursion
nataleya2010, 2022-03-30 22:26:48

How to display the answer in one line when recursing?

We need to find all the factors of the number and print them in ascending order. For example: 18=2*3*3. It turned out to find, but to display them as required in the task - no. How to do it? My code:

function dividerFunctionTo(num, divider=2) {
    if(num<=0){console.log("введите число больше нуля");return;}
    if (num==1){return divider=1;}else
    if (num%divider==0){
        console.log(`${num} || ${divider}` );
        return dividerFunctionTo(num/divider, divider);
    }else
    {
        return dividerFunctionTo(num, divider+1);
    }

}

let numberFixedTo = +prompt("введите число");
dividerFunctionTo(numberFixedTo);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2022-03-30
@nataleya2010

Instead of printing the current result to the console, return an array consisting of the current result and the results of the recursive call:

function getDividers(num, divider) {
  return num === 1
    ? []
    : num % divider
      ? getDividers(num, divider + 1)
      : [ divider, ...getDividers(num / divider, divider) ];
}

Well, with the resulting array, you can do what you need there:
function showDividers(num) {
  if (!Number.isInteger(num) || num < 2) {
    throw 'fuck off';
  }

  console.log(`${num} = ${getDividers(num, 2).join(' * ')}`);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question