steph
steph

Reputation: 55

Finding the greatest prime factor of an integer in Javascript

I am trying to write a simple program to find the greatest prime factor of an integer in JavaScript. The code I have written to do this follows:

let ans;

function factor(target, half) {
    for (let i = 2; i < half; i++) {
        if (target % i == 0) {
            ans = target / i;
            factor(ans, ans / 2);
        }
    }
}

factor(30, 15);
console.log(ans);

Now whether or not this code is an efficient solution to the problem or if it even works at all is beyond my issue with it: When I follow breakpoints set at each line of the factor function, I see that right after i = 2, target = 5, half = 2.5, and ans = 5, the value of target and half jump back up to 15 and 7.5 respectively. However, I do not see where in my code the values are told to change.

Upvotes: 1

Views: 66

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074168

You're calling the function recursively, and each call to the function gets its own target, half, and i variables. In the first call to factor, target is 30 and half is 15. Then you call it again with the arguments 15 and 7.5; that inner call to factor gets its own target (15) and half (7.5), but the outer call still has its copies (30) and (15). This continues when you call factor again recursively, creating a third set, etc. When you step out of the innermost call, its variables disappear and you see the ones that are for the call that called it.

It may be clearer with a simpler example:

function countdown(value, indent) {
    var twice = value * 2;
    console.log(indent + "[before] value = " + value + ", twice = " + twice);
    if (value > 0) {
        countdown(value - 1, indent + "  ");
    }
    console.log(indent + "[after]  value = " + value + ", twice = " + twice);
}
countdown(3, "");
.as-console-wrapper {
    max-height: 100% !important;
}

The output of that is:

[before] value = 3, twice = 6
  [before] value = 2, twice = 4
    [before] value = 1, twice = 2
      [before] value = 0, twice = 0
      [after]  value = 0, twice = 0
    [after]  value = 1, twice = 2
  [after]  value = 2, twice = 4
[after]  value = 3, twice = 6

As you can see, the values for value and twice in the outer call aren't changed by making the inner call. Each call gets its own set of variables.

Upvotes: 2

Related Questions