javascript - Why does my loop gone infinite loop? -


i writing function find prime factors of number. in function, has got 2 loops. 1 finding factors, finding prime factors first loop. second loop has gone infinite, haven't spotted anywhere in loop make infinite. did miss?

function findprimefactors(num) {  var factors = [];  var primefactors = [];  var currindex = 0;  var initfactorslen;  var currcompose;  (i = 1; <= num; ++i)  {   if (num % == 0)   {    factors.push(i);   }  }  var initfactorslen = factors.length;  (i = 0; <= initfactorslen; ++i)   {  //this infinite loop   console.log("i " + + " , factors " + factors);   currcompose = factors[i];   var primetest = isprime(currcompose);    if (primetest == true)   {    primefactors.push(currcompose);   }  }  return primefactors; }  function isprime(num) {  var sqrtnum = math.sqrt(num);  var ceilednum = math.ceil(sqrtnum);  if (num == 1 || num == 0)  {   return false;  }  else if (num == 2)  {   return true;  }  else  {   (i = 2; <= ceilednum; ++i)   {    if (num % == 0 && != num)    {     return false;    }   }   return true;  } } 

i've notice doesn't gone infinite, returns 1 prime number although has 2. (try findprimefactors(143))

thanks,

your i loop variable global, both functions share same values i.

initialize and declare var, this:

for (var = 0; <= initfactorslen; ++i) 

an alternative declaring within loop statement declare other variables. note can declare variables in comma-separated list, this:

var factors = [],     primefactors = [],     currindex = 0,     initfactorslen,     currcompose,     i; 

also note don't need explicitly check truthness. this:

var primetest = isprime(currcompose);  if (primetest == true) {   primefactors.push(currcompose); } 

… equivalent this:

var primetest = isprime(currcompose);  if (primetest) {   primefactors.push(currcompose); } 

… or more simply:

if (isprime(currcompose)) {   primefactors.push(currcompose); } 

Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -