Sam
Sam

Reputation: 3

Javascript : How can I add X elements to an array

I need to create an array including the first 100 prime numbers, here is my code:

var premier= [];
var nombre= premier.length;

function isPrime(n)
{
    if(n < 2)
    {
        return false;
    }

    for(i=2; i<Math.sqrt(n); i++)
    {
        if(n%i===0)
        {
            return false;
        }
    }
    return true
};

while(nombre<100)
{
    var j=2
    if(isPrime(j)==true)
    {
        premier.push(j);
    }
    j=j+1
}

I am a beginner in Javascript, but I have tested the isPrime function and it works fine even forlarge numbers.

but when I run the program I have:

FATAL ERROR: JS Allocation failed - process out of memory

I think this part is wrong:

while(nombre<100)
{
    var j=2
    if(isPrime(j)=true)
    {
        premier.push(j);
    }
    j=j+1
}
console.log(premier)

But I can't tell why

Upvotes: 0

Views: 632

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324760

You are repeatedly setting j=2 every time the loop runs, and you never change nombre so the loop will never end. Note that JavaScript sets literal vaues by value, not by reference, so nombre = premier.length won't magically update.

Additionally, statements of the form if( x = true) will set x to true, and then pass the condition automatically. In this case, since x is a function call, it is invalid syntax.

Did you mean this?

var j = 2;
while(premier.length < 100) {
    if( isPrime(j)) premier.push(j);
    j++;
}

Upvotes: 3

Related Questions