简体   繁体   English

查找小于输入的所有素数

[英]Finding all Prime Numbers less than an input

I have an input field to take a maximum number and find all smaller prime numbers. 我有一个input field来取最大数字并找到所有较小的数。

It should return to an array and display the array with an alert . 它应该返回一个array并显示带有alertarray

Except I'm getting blank every time. 除了我每次都变得空白。

HTML: 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: CSS:

#go, #number {float:left;}

JavaScript: 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/ 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 . 当然它会被1整除。

A revised and working jsfiddle 一个修改和工作的jsfiddle

JavaScript: 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 名为“isPrime(x)”的东西预计会返回一个布尔值

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 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 -- changed isPrime to return boolean, added findPrimes to return an Array, and other features mentioned above JS - 改变了isPrime以返回布尔值,添加了findPrimes以返回一个Array,以及上面提到的其他功能

// 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 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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