0

I recently started learning java-script. I created a program which checks whether a number is a prime number or not. But I wanted to get all prime numbers from 1 to 100 at once without checking individually for each number. please show me how to get it done.(edit) I want them to be on the html page and not in the console

<!DOCTYPE html>
<html>
    <head>
        <title>
            Check For Prime
        </title>
        <link rel="stylesheet" href="prime.css">
        <script rel="text/javascript" src="prime.js"></script>
    </head>
    <body>
        <div class="main">
            <h1>Check for Prime</h1>
            Enter Number : &nbsp; <input id="num"><br><br>
            Number is : &nbsp; <input id="ans"><br><br>
            <button id="bt1" onclick="check()">Check</button><br><br>
            <button id="bt2" onclick="clr()">clear</button>
        </div>
    </body>
</html>

function check(){
    var n = Number(document.getElementById("num").value);
    var c = 0;


    //for numbers 1 and 2
    if(n == 1){
        document.getElementById("ans").value = "Not Prime";
    }
    if(n == 2){
        document.getElementById("ans").value = "Prime";
    }


    //for numbers other than 2
    //increments c every time (x % n) is 0
    for(x = 1 ; x <= n; x++){
        if((n % x) == 0){
            c = c + 1;
        } 
    }


    //for prime numbers c should be equal to two
    //prime numbers have only two positive factors
    if(c == 2){
        document.getElementById("ans").value = " Prime ";
    }
    else{
        document.getElementById("ans").value = "Not Prime";
    }

}

//clear function
//clear input
function clr(){
    document.getElementById("num").value = "";
    document.getElementById("ans").value = " ";
}
Tabeed-H
  • 3
  • 4
  • Not the answer you probably want, but if you need to have the prime numbers less than 100 on tap, just put them into a constant array somewhere in your code. – Tim Biegeleisen Jul 06 '19 at 16:01

1 Answers1

0

This is how you can get the prime numbers without individual checks:

const isPrime = n => [...Array(n).keys()].slice(2).every(divisor => n % divisor !== 0)

const primeNumbers = [...Array(101).keys()].filter(isPrime)

console.log(primeNumbers)
antonku
  • 7,377
  • 2
  • 15
  • 21