Wednesday, 15 July 2015

javascript - Why does my loop gone infinite loop? -


I am writing a function that will find the key factors of a number. In that ceremony, it has two loops, to find the factors, the second loop has become infinite to find the main factor from the first loop, I have not seen anywhere in the loop which can make it infinite Where can I miss is?

  get found pimfactors (num) {var factor = []; Var prime factor = []; Var currIndex = 0; Var initFactorsLen; Var currCompose; (I = 1; i & lt; = num; ++ i) {if (number% i == 0) {factors.push (i); }} Var initFactorsLen = factors.length; (I = 0; i & lt; = initFactorsLen; ++ i) {// This is infinite loop console.log ("I" + + + "and factor" + factor); CurrCompose = factor [i]; Var Primitest = ISprimem (Corpora Composse); If (primetist == true) {primefacts; currCompose; }} Return prime factor; } Function isPrime (num) {var sqrtNum = Math.sqrt (num); Var ceiledNum = Math.ceil (sqrtNum); If (num == 1 || num == 0) {return false; } And if (num == 2) {back true; } Else {for (i = 2; i & lt; = ceiledNum; ++ i) {If (num% i == 0 & amp; i! = Num) {return false; True} true; }}  

I also noted that sometimes it does not go infinite, but it only gives a major number, though it is 2. >

Your i loop variable is global, so both functions share the same values ​​for i .

Declare it with and declare with var , like this:

 for  (var i = 0; i & lt; = initFactorsLen; ++ i)  

An option to declare it in the loop statement is to declare it with its other variables, note that you have all your variables Can be declared in a comma-separated list, such as:

  var factor = [], primefactors = [], cruel index = 0, init factars, curl compos, i;  

Also keep in mind that you do not need to check the truth clearly:

  var primeTest = isPrime (currCompose); If (primetist == true) {primefacts; currCompose; }  

& hellip; This is equivalent to:

  var primetime = currCompose; If (primatest) {primefacts; currCompose); }  

& hellip; Or more easily:

  if (isPrime (currCompose) {primeFactors.push (currCompose); }  

No comments:

Post a Comment