Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding all Prime Numbers less than an input

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/

like image 560
Nicholas Hazel Avatar asked Nov 11 '22 07:11

Nicholas Hazel


1 Answers

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=[];
});
like image 132
Nicholas Hazel Avatar answered Nov 15 '22 07:11

Nicholas Hazel