闲来看了一篇博客:闲聊质数,看后自己动手研究了输出质数的方法,计算质数的效率有所提高.
下面是改进后的代码:
使用索引存储质数
<!DOCTYPE HTML> <html> <head> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" /> <title>prime</title> <style> #wrap{ width:320px; margin:0 auto; text-align: center; } #output{ text-align:left; } var{ color:red; } </style> </head> <body> <div id="wrap"> <h1>算质数</h1> <br> <div> <input id="max" type="text" />以内的质数 <input type="button" id="button" value="计算" /> </div> <br> <div id="output"></div> </div> <script> button.onclick = function() { var value = max.value; output.innerHTML = "<var>计算中...</var>"; if (value) { //获取质数数组 var startTime = (new Date()).getTime(); var arr = getPrime2(parseInt(value)); var nowTime = (new Date()).getTime(); var time = (nowTime - startTime) / 1000; // var str = arrToString(arr); str = "<strong>" + value + "</strong> 以内的质数有<strong> " + arr.length + " </strong>个:<var>(计算耗时" + time + "秒)</var><br>" + str; // output.innerHTML = str; } else { output.innerHTML = "<var>请输入素数的范围</var>"; } } function arrToString(arr) { //数组转化为字符串 return arr.join(" "); } function getPrime2(max) { //获取max以内的质数 var prime = []; for (var i = 2; i <= max; i++) { if (isPrimeNum(i, prime)) { prime.push(i); } } return prime; } function isPrimeNum(n, arr) { if (n < 2) { return false; } if (n == 2) { return true; } if (!arr || !arr.length) { return false; } for (var p = 0; p < arr.length; p++) { if (n % arr[p] == 0) { return false; } } return true; } </script> </body> </html>