javascript 显示一定范围内的素数(质数)

素数又称质数,是大于1的自然数,并且只有1和它本身两个因数。

具体实现代码如下:

<!DOCTYPE HTML>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script type="text/javascript" src="https://files.cnblogs.com/greenteaone/jquery-2.1.3.min.js" charset="utf-8"></script>
    <title></title>
</head>
<body>
<script type="text/javascript">
    //方法1,当要求取得超过5000范围内的素数时,此法耗时少
    function printPrime1(){
        var t1=new Date();
        var n=$("#number").val();
        var status=0;
        var numbers='方法1:2,3';
        var all=2;
        console.log('素数=',2);
        for(var i=5;i<n;i++){
            for (var j = 2; j <= Math.sqrt(i); j++) {
                if (i % j == 0) {
                    status = 0;
                    break;
                } else {
                    status = 1;
                }
            }
            if(status==1){
                numbers=numbers+','+i;
                all=all+1;
            }
        }
        var t2=new Date();
        var t=parseFloat(t2-t1);
        $("#showTime1").html(t);

        $('#all1').html('总的素数'+all+','+numbers);
    }
    //方法2:当要求取得小于5000范围内的素数时,此法耗时跟方法1相差不大
    function printPrime2(){
        var t1=new Date();
        var n=$("#number").val();
        var status=0;
        var all=1;
        var numbers='方法2:2';
        for(var i=3;i<n;i++){
            for(var k=2;k<i;k++){
                if(i%k==0){
                    status=0;
                    break;
                }else{
                    status=1
                }
            }
            if(status==1){
                numbers=numbers+','+i;
                all=all+1;
            }
        }
        var t2=new Date();
        var t=t2-t1;
        $("#showTime2").html(t);
        $('#all2').html('总的素数'+all+','+numbers);
    }
    function clearNumbers(){
        $('#all1').html('');

        $('#all2').html('');
    }
</script>
<style type="text/css">
    input{
        text-align: center;
        height:30px;
        border:1px solid #CCC;
        border-radius: 3px;
        box-shadow:3px 3px lavender ;
    }
    button{
        box-shadow: 2px 3px lavenderblush;
        height: 30px;
        border-radius: 13px;
        border: 1px solid #ccc;
        background: coral;
    }
    label{
        width: 60px;
    }
    p{
        width:90%;
        margin:auto;
        word-break: break-all ;
        line-height: 30px;
    }
    div{
        width:90%;
        margin:auto;
    }
</style>
<div>

    <input type="text" id="number" placeholder="请输入数字" onfocus="clearNumbers()"  />
    <button onclick="printPrime1()" >打印素数(方法1)</button>
    <label>耗时</label>
    <label id="showTime1"></label>
    <button onclick="printPrime2()" >打印素数(方法2)</button>
    <label>耗时</label>
    <label id="showTime2"></label>
</div>
<P id="all1" mode="wrap"></P>
<P id="all2"></P>
</body>
</html>

 

posted @ 2015-01-08 16:02  绿茶叶  阅读(6620)  评论(0编辑  收藏  举报