Jephrocs
Jephrocs

Reputation: 3

Returning array of prime factors with recursion

Here is my code. I am trying to push my factors into an array but I'm unable to and stuck on what to do. I get the factors just fine when I console.log it. Any help would be greatly appreciated.

primer = (num, factor = 2,) => {
    const factors = []
    if (num < 2) {
        return factors
    }
    if (num % factor == 0) {
        factors.push(factor)
        console.log(factor)
        primer(num / factor, factor);
    }
    else {
        primer(num, factor + 1);
    }

}

Upvotes: 0

Views: 413

Answers (1)

Mingwei Samuel
Mingwei Samuel

Reputation: 3282

The problem is that factors = [] is a different array every time you recursively call the function. You need to make sure to add your recursive results to your current results:

primer = (num, factor = 2) => {
    const factors = [];
    if (num < 2) {
        return factors;
    }
    if (num % factor == 0) {
        factors.push(factor);
        factors.push(...primer(num / factor, factor, factors));
    }
    else {
        factors.push(...primer(num, factor + 1, factors));
    }
    return factors; // And remember to return!
}

Note that we're creating a new array every time we recurse above, which isn't ideal. Another way to do this while avoiding creating new arrays would be to use an extra factors array param and make sure to append to it:

primer = (num, factor = 2, factors = []) => {
    if (num < 2) {
        return factors;
    }
    if (num % factor == 0) {
        factors.push(factor);
        primer(num / factor, factor, factors);
    }
    else {
        primer(num, factor + 1, factors);
    }
    return factors;
}

Upvotes: 1

Related Questions