使用Java脚本打印1到100之间的所有素数

时间:2019-07-06 15:58:40

标签: javascript html

我最近开始学习Java脚本。我创建了一个程序来检查数字是否是质数。但是我想一次获取所有从1到100的质数,而不必分别检查每个数字。请告诉我如何完成此操作。(编辑)我希望它们位于html页面而不是控制台中

<!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 = " ";
}

1 个答案:

答案 0 :(得分:0)

这是无需单独检查即可获得质数的方法:

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

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

console.log(primeNumbers)