我有input field
取最大数字并找到所有较小的 prime 数字。
它应返回array
并显示array
alert
。
除非我每次都变得空白。
HTML:
<p>Please enter the maximum number you'd like to find all prime numbers below it for.</p>
<p><input type="text" id="number" /></p>
<button id="run">RUN</button>
CSS:
#go, #number {float:left;}
JavaScript的:
var primes=[];
function isPrime(x){
var prime=true;
for(var i=0;i<=Math.sqrt(x);i++){
if(x%i===0){
prime=false;
}
}
if(prime){
primes.push(x);
}
};
$('#run').on('click',function(){
var total=$('#number').val();
for(var j=2;j<=total;j++){
isPrime(j);
}
alert(primes);
});
答案 0 :(得分:1)
这就是问题:
for(var i=0;i<=Math.sqrt(x);i++){
当然它会被1
整除。
修订后的working jsfiddle
JavaScript的:
var primes=[];
function isPrime(x){
var prime=true;
for(var i=2;i<=Math.sqrt(x);i++){
if(x%i===0){
prime=false;
}
}
if(prime){
primes.push(x);
}
};
$('#run').on('click',function(){
var total=$('#number').val();
for(var j=3;j<=total;j++){
isPrime(j);
}
alert(primes);
primes=[];
});
答案 1 :(得分:0)
可以而且应该在最初发布的代码中进行一些改进:
要求达到共同的专业标准:
在我看来,有很好的功能
HTML - 添加了一个包含答案的div
<p>Please enter the maximum number you'd like to find all prime numbers below it for.</p>
<p><input type="text" id="number" /></p>
<button id="run">RUN</button>
<br/>
<div id="answer"></div>
JS - 改变isPrime返回布尔值,添加findPrimes返回一个数组,以及上面提到的其他功能
// try to grab our prime list out of browser localstorage
try {
window.primes = JSON.parse(window.localStorage["primes"]);
console.log("retrieved "+window.primes.length+" primes from storage");
// print the seed primes to the console in case of bug
console.log(window.primes);
} catch(e){};
// seed it with a few primes if empty
if (typeof(window.primes)!=="object") window.primes=[2,3,5,7];
function isPrime(x){
// isPrime takes x and returns a Boolean if x is Prime
var prime=false, i=0,l=primes.length;
var maxprime=primes[l-1];
var reqprime = Math.floor(Math.sqrt(x));
if (reqprime>maxprime) {
findPrimes(reqprime);
// the primes list has changed, set l again
l = primes.length;
}
while( (i<l) && (x%primes[i]!==0) && (primes[i]<=reqprime) ) ++i;
prime = ( (i===l) || (primes[i]>reqprime) );
// if i is l then x is prime
// if we have checked all the primes up to sqrt(x) then x is prime
return prime
};
function findPrimes(x){
// findPrimes finds new primes up to and including x
// returns an Array of prime numbers
var i=0,result=[],l=primes.length;
var maxprime=primes[l-1];
if (x>maxprime){
for(i=maxprime+2; i<=x; i+=2){
if (isPrime(i)) primes.push(i);
}
l=primes.length;
// try to set browser localstorage with new list of Primes
// fail with console message only
try {
window.localStorage["primes"]=JSON.stringify(primes);
} catch(e){ console.log("cant set primes in localStorage"); };
}
i=0;
while( (i<l) && (primes[i]<=x)){
result.push(primes[i]);
++i;
}
return result;
}
$('#run').on('click',function(){
var total=$('#number').val();
var answer = findPrimes(total);
$('#answer').html("<ul><li>"+
answer.join("</li><li>")+
"</li></ul>"
);
});