Need to generate prime numbers in JavaScript

NilR picture NilR · Feb 23, 2014 · Viewed 54.1k times · Source

I am writing a JavaScript to generate prime numbers from 2 to 100. However It doesn't work and can't figure it out.

will you help me please?

var array = new Array(100);

for (var i=2 ; i<=array.length-1; i++) {
    if((i%2===0) || (i%3===0))
        continue;
    document.writeln(i+",");
}

I modified my answer, but now it doesn't print 2 & 3; how can I include 2 & 3... result is :

5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, 53, 55, 59, 61, 65, 67, 71, 73, 77, 79, 83, 85, 89, 91, 95, 97

Answer

nanobash picture nanobash · Feb 23, 2014
function isPrime(num) {
    for ( var i = 2; i < num; i++ ) {
        if ( num % i === 0 ) {
            return false;
        }
    }
    return true;
}

function display(n) {
    var arr = [2];
    for ( var i = 3; i < n; i+=2 ) {
        if ( isPrime(i) ) {
            arr.push(i);
        }
    }
    console.log(arr); // use arr result on your own
}

display(100);

NOTE: Specify n parameter in display function and get the primes from 2 to n ...

Check out JSFiddle

Updateing: Note that the above script is correct and I'm leaving it, though adding the same function with one functionality in addition:

function prime(n,flag) {
    ( typeof flag === "undefined" || flag === false ) ? flag = false : flag = true;

    function isPrime(num) {
        if ( num === 0 || num === 1 ) {
            return false;
        }
        for ( var i = 2; i < num; i++ ) {
            if ( num % i === 0 ) {
                return false;
            }
        }
        return true;
    }

    if ( flag ) {
        var arr = [2];
        for ( var i = 3; i <= n; i+=2 ) {
            if ( isPrime(i) ) {
                arr.push(i);
            }
        }
        return arr;
    } else {
        return isPrime(n);
    }
}

Explanation: prime function expect two parameters, first one is required and the second is optional. If only first parameter is specified function will return true or false based on number belongs or not to primes. If second parameter is specified as true (or any other type except undefined and false) function will return array of primes from 2 to n. For example:

console.log(prime(2)); // returns true ( 2 is prime )
console.log(prime(8)); // returns false ( 8 isn't prime )

console.log(prime(100,true)); // returns [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]