Sunday, August 19, 2018

JavaScript - Large Index Values Lead to Infinite Loops - Not Sure Why?

I'm working on a Project Euler problem (#3) - Largest Prime Factor.

The code I have written seems to work for smaller numbers but not for bigger numbers (see 2nd invocation of the function). If I try that, it goes into an infinite loop and I can't figure out why. I've tried JSBin to test and it does the same thing ('potential infinite loop') so I have no idea how to debug this issue.

Would appreciate help with this.

Here's my code:

  //Prime Checker
  var isPrime = function (num) {
    for(var i = 2; i < num; i++) {
      if(num % i === 0) {
        return false;
      }
    }
    return true;
  }; //end function

  //Largest Prime Factor
  var primeFactor = function (num) {
    var result = 0;
    var temp = 0;
    var primeArr = [];

    for (var i = 2; i <= num; i++) {
      if (num % i === 0) {
        temp = i;
        if (isPrime(temp)) {
          primeArr.push(temp);
        }
      }
    }
    console.log("primeArr: " + primeArr);

    //sort
    primeArr.sort(function(a,b) {
      return b - a;
    });

    result = parseInt(primeArr[0]);
    console.log("result: " + result);        
    return result;
  }; //end function

  primeFactor(13195); //WORKS FINE
  primeFactor(600851475143); //CAUSES INFINITE LOOP

Solved

As mentioned in one of the comments, if JavaScript runs out of memory in a math equation it can sometimes lead to infinite loops through things such as memory links. If you need a solution, there are some JavaScript libraries such as big.js that handle large math equations, however I don't know if it will be able to help this. The only way to find out is to try. Hope this helps.


No comments:

Post a Comment