Answer the question
In order to leave comments, you need to log in
How to find the smallest divisor in an iterative process of recursion?
I'm taking a course on the basics of Hexlet programming.
In the problem of an iterative process, where you need to find the smallest divisor of a given number, there was a hard stack. Here is my code:
const smallestDivisor = (num) => {
const iter = (counter, acc) => {
if (counter === 1) {
return 1;
}
if (counter % acc) {
return acc;
}
return iter(counter, acc + 1);
};
return iter(num, 4);
};
Answer the question
In order to leave comments, you need to log in
Read the assignment more carefully.
Try to decompose the algorithm in simple words in your head.
1. We pass the number num to the function (for example, 9)
2. We create a variable acc with an initial value of 2 (we do not need 1)
3. We divide num by acc.
4. Share without a trace? (9 % 2) This is the smallest divisor, return it.
5. Don't share? Add +1 to acc and try again.
6. Reached acc = num? We return num.
Accordingly, from point 2 to 6 is a recursion that works with acc.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question