Search code examples
javascriptalgorithmprime-factoring

Browser Crashes when trying to get Largest Prime Factor of a number (Javascript)


Below is the code. When calling the function largestPrime(number) with a number parameter of either small (5 digit) or large (12 digit) number this code crashes the browser every time regardless. I have reviewed it closely, but still no idea what's going wrong. Please don't answer with a different solution to this objective, I would like to understand what is wrong with my code. Thanks!


var sqRoot = function(n) {
return Math.sqrt(n);
}

var isInt = function(n) {
if(n%1 === 0) {
  return true;
}
  else {
    return false;
  }
}

var primeCheck = function(n) {
var res = true;
var y = 2;
while(y <= sqRoot(n) && res === true) {
  if(!isInt(n) || isInt(n/y)) {
    res = false;
  }
  else {
    y+=1;
  }
}
return res;
}

var largestPrime = function(n) {
var y =2;
var temp = true;
var res = n/y;
while(temp === true) {
  if(primeCheck(res)) {
    temp = false;
  }

  else {
  y+=1;

  }
}
return res;
}


largestPrime(/*here goes the number to be evaluated*/)

Solution

  • Your res in largestPrime has never been changed in the loop body so the program got an infinity loop.