素數又稱質數,是大於1的自然數,並且只有1和它本身兩個因數。
具體實現代碼如下:
<!DOCTYPE HTML> <html> <head lang="en"> <meta charset="UTF-8"> <script type="text/javascript" src="http://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>