How can I make this recursive javascript output to anything other than the console

This is the inspiration behind Project Euler Q3. So you've seen it all before. If you haven't seen this, → https://projecteuler.net/problem=3

I am not after resolving the issue.

Recursion is still very helpful for me. I hit this code, it gives me the right solution (well it gives me the right factors), however I can only get it to output to the console, whereas I would like to get it to return a value that could be used elsewhere. possibly for kind or max / min. I was thinking maybe an array with factors in it. However, my understanding is that whenever I initialize an array inside a function, it gets reinitialized with every recursive call to the function. So it didn't work.

function primefy(n) {
    var isPrime = true;
    for (var i = 2; i < n; i++){
        if(n % i === 0){
            isPrime = false;
            console.log(i);
            primefy(n/i);
            break;
        }
    }
    if (isPrime){
        console.log(n);
    }
}

primefy(prompt("A number please?"));

      

if I feed it 8 it will log 2 2 2, 18 gives 2 3 3 and so on. The math seems to be correct, but it is clear that the implementation is not working.

+3


source to share


1 answer


To return a value from a recursive process (rather than just doing some things along the way), each function instance must return something before the instance that called it (or outside of the original call if it's the root instance). To do this, it needs to combine its local results with the results passed to it by its children.

For example:

function primeFactors(n) {
    for (var i = 2; i < n; i++){
        if(n % i === 0){
            return [i].concat(primeFactors(n/i));
        }
    }
    return [n];
}

      



Please note that we don't need isPrime

any more or break

because we are going return

as early as possible. When we go back to the root, we have created an array containing all the factors I found. I've renamed the function to better reflect what it actually returns, but that's personal taste.

(By the way, you don't have to completely loop on n

; you are guaranteed not to have a factor between Math.sqrt(n)

and n

within that loop.)

+3


source







All Articles