简体   繁体   中英

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/

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=[];
});

There are several improvements that can, and should, be made in code like that originally posted:

Required to meet common professional standards:

  • something called "isPrime(x)" is expected to return a Boolean

Nice features to have, in my opinion

  • Show the output on the page rather than an alert
  • Use a list of primes to check an unknown number rather than checking every integer for divisibility
  • Store the list of primes and reuse it between button pushes to speed up additional use
  • Store the list of primes in browser storage to speed up future use

HTML -- added a div to contain the answer

<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 -- changed isPrime to return boolean, added findPrimes to return an Array, and other features mentioned above

// 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>"
                      );
});

JSFIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM