I am attempting to generate an array containing the first 100 prime numbers. Here is the code I have written:
var primeArray= [];
var num= primeArray.length;
function checkIfPrime(n)
{
if(n < 2)
{
return false;
}
for(i=2; i<Math.sqrt(n); i++)
{
if(n%i===0)
{
return false;
}
}
return true
};
while(num<100)
{
var j=2
if(checkIfPrime(j)==true)
{
primeArray.push(j);
}
j=j+1
}
As a beginner in Javascript, I have verified that the checkIfPrime
function works well even with large numbers.
However, upon running the program, I encounter the following error:
FATAL ERROR: JS Allocation failed - process out of memory
I suspect there might be an issue with this part of the code:
while(num<100)
{
var j=2
if(checkIfPrime(j)=true)
{
primeArray.push(j);
}
j=j+1
}
console.log(primeArray)
But I cannot pinpoint the exact problem.