输出质数的方法改进
閑來看了一篇博客:閑聊質數,看后自己動手研究了輸出質數的方法,計算質數的效率有所提高.
下面是改進后的代碼:
使用索引存儲質數
<!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>?
?
?
?
?
?
轉載于:https://www.cnblogs.com/tgcoy/p/3145987.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
- 上一篇: BZOJ 3218(a + b Prob
- 下一篇: PHP中遍历stdclass objec