I have an input field
to take a maximum number and find all smaller prime numbers.
It should return to an array
and display the array
with an alert
.
Except I'm getting blank every time.
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);
});
http://jsfiddle.net/jH5jq/1/
This was the problem:
for(var i=0;i<=Math.sqrt(x);i++){
Of course it'll find divisible by 1
.
A revised and 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=[];
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With