Search code examples
javascriptprimes

Prime Number in JavaScript


I wrote code in JavaScript to find Prime Numbers.

I've created an Array (var arr) and put the first prime number in it.

I want to check the i value with last prime number stored in the array (instead of all number for faster run.)

Checkout my code and please correct my syntax.

var arr = [2];
document.getElementById("demo").innerHTML = arr;

function myFunction() {

for (i = 3; i <= 10; i++) {
    if (i % 2 !==0) {
        for (j = 0; j <= arr.length - 1; j++){
            if (i % arr[j] !== 0) {
                arr.push(i);
            }
        }
        document.getElementById("demo").innerHTML = arr;    
    }
}


Solution

  • The suggested algorithm by the OP may have a problem, even though it works on a limited range of numbers from 2 to 10 to produce the expected results of 2,3,5,7 after correcting the code. Unfortunately, if the range of numbers is enlarged, then non-prime numbers can creep in, as demonstrated below:

    var arr = [2];
    
    function myFunction() {
    
        for (i = 3; i <= 30; i++) {
            if (i % 2 !==0 && i % Math.sqrt(i) !==0) {
                for (j = 0; j <= arr.length - 1; j++){
                    if (i % arr[j] !== 0) {
                        arr.push(i);
                    }
                    break;
                }
            }
        }
        document.getElementById("demo").innerHTML = arr;
    }  
    myFunction();
    <div id="demo"></div>

    The following code may be less efficient but the upside is that it works no matter how large the range of numbers. The solution derives from code borrowed and modified from here and here.

    var arr = [2];
    
    function isPrime( n ) {
    
        
       // eliminate non-integers 
       if (  n != Math.round(n)  ) {
          return false;
       }
       
       // assume n is prime and test if true
       for(var i=2, max=Math.sqrt(n); i <= max; i++) {
           if ( n % i === 0 ) {
               return false;
           }
        }
        return n > 1;
    }
    
    function myFunction() {
    
        for (i = 3; i <= 30; i++) {
          if ( isPrime(i) ) {
              arr.push(i); 
          }// end-if
        }// end-for
        document.getElementById("demo").innerHTML = arr;
    }
    
    myFunction();
    <div id="demo"></div>

    Note, the array starts initially with prime number 2 and as the code encounters prime numbers within the specified range they are added to the array. Incidentally, you need an HTML DIV tag with an id of "demo" for this to work. And, you only need to assign the array to the innerHTML property of the div element once, after the loop has finished processing. Lastly, you need to call myFunction().

    Interesting related discussion here.