N
N
Nikolai Mitsula2019-11-10 19:48:50
JavaScript
Nikolai Mitsula, 2019-11-10 19:48:50

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);
};

I'm trying to find the smallest divisor for the number 4, which is the 2nd.
I don’t want to spoil the decision from Hexlet, I want to understand how to solve it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
McBernar, 2019-11-10
@McBernar

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 question

Ask a Question

731 491 924 answers to any question