0

I am creating a web page that will find the prime factorization of a number. The function I use calls itself from within a loop. After I execute the function within itself, the index of the loop is changed from the index that it reached from the second calling. It should return all prime factors in an array. Here is the code.

function pf(num){
    max=Math.floor(Math.sqrt(number));
    factors=[];
    prime=true;
    for(count=2;count<=max;count++){
        ratio=num/count;
        if(ratio%1==0){
            alert(count);//HERE
            factors=pf(ratio);
            alert(count);//HERE
            factors.push(count);
            prime=false;
            break;
        }
    }
    if(prime){
        factors.push(num);
    }
    return factors;
}

Say this code runs with an input of 20. The first alert will show the number 2, but the next one will show 3. Is there a way to make the current index of the loop not changed by the second calling of the function?

0

2 Answers 2

4

You really should use var for all your variables unless you specifically want them to be global. var makes the variable local to the executing context, in this case the function pf. Without it, all your variables are global, probably on the window context if you are running this in a browser.

I suspect your issue occurs because max and/or count is global.

do

var max = Math.floor(Math.sqrt(number));

and

for(var count=2;count<=max;count++){

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I guess this is what I get for never typing var.
2

The variables in your function are all so called global variables. This means they can (and will) be changed from everywhere in your script. Also they keep their values after your function finishes. So they have different initial values on each function call.

To keep the variables inside your function you've to define them as local. This can be done with the keyword var when defining the variable the first time.

Just write

function pf ( num ) {
    var max = ...
    var factors = ...

and so on.

This is the better and cleaner way and helps you to avoid such bugs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.