简体   繁体   中英

JavaScript Find Prime Numbers

I have to set all the indexes in an array equal to 1. Then I have to find which indexes are not prime and set them equal to 0. Then print out all the indexes of the array that are equal to 1(prime).

I can't get the part that sets the index to 0 if it is not prime. My output now is it just prints every number from 2-100. Can you help me figure out the condition that determines if the index is prime?

<script>
var primeArray = new Array();
for(var i = 0; i < 101; i++){

    primeArray[i] = 1;
    //document.writeln(" " +  primeArray[i]);

}

primeArray[0] = 0;
primeArray[1] = 0;
//document.writeln("" +primeArray[0]);
//document.writeln("" +primeArray[1]);


for(var j = 2; j < 101; j++){

    if(primeArray[j] == 1){

        for(var k=j+1; k<101; k++){
            //var test = j%k;
            //document.writeln("" + test);
            if(j%k == 0){
                primeArray[j]=0;
            }   
        }           
    }
    //if(primeArray[j] == 1){
    //document.writeln("" + primeArray);
    //}
}
document.writeln("" + primeArray)
</script>

What you've been assigned is an approach to finding prime numbers that dates back to ancient Greece. It's a simple, straightforward process.

  1. Create an array of the desired size (maximum prime number), and initialize it to some value (in your case, all 1 ).
  2. Initialize a "trial" value to 2.
  3. Check the array element whose index is the trial value. If the element value is 1, then the trial value is prime. Starting from the trial value added to itself, iterate through the array setting multiples of the trial value to 0. (If the trial entry is zero, it's not prime and no more work is necessary.)
  4. Increment the trial value and continue at step 3, stopping when the trial value exceeds the length of the array.

When the iteration completes, the entries in the array containing 1 are prime numbers.

Note that with this technique, no multiplication or division is required; just addition.

Your loop tests for j%k == 0, but k is always greater than j because your loop for k starts at j+1 and keeps getting bigger, so j%k will always equal j.

I think your loop should be

for(var k=j-1; k>1; k--)
{
    if(j%k == 0)
    {
      primeArray[j]=0;
      break; // it's not prime, so move on to the next value for j.
    }   
}

This isn't optimal prime-finding code, but it will get the right results.

I will give a function that you will call to know if a given number is prime or not. To test it, create a text file, rename it prime.html (for example), and paste next code :

<html>
  <head>
    <title>Prime</title>
    <script type="text/javascript">

var X = new Array( 1,2,3,4,5,6,7,8,9 );

function arr () {
var i;
for ( i = 0; i < X.length; i++ )
  if ( is_prime( X[ i ] ) )
       alert( X[ i ] + " -> set to 1" );
  else alert( X[ i ] + " -> set to 0" );
}

function check_prime () {
var num = document.getElementById( "txt" ).value;
if ( is_prime( parseInt( num ) ) )
     alert( "Is prime" );
else alert( "Is NOT prime" );
}

function is_prime ( num ) {
var i;
for ( i = 2; i < num; i++ )
  if ( ( num % i ) == 0 )
     return false;
return true;
}
    </script>
  </head>
  <body>
    Enter a number
    <input type="text" id="txt" />
    <br/>
    <button onclick="check_prime()">Check if prime</button>
    <br/>
    <button onclick="arr()">Check array</button>
  </body>
</html>

Save it and double click prime.html. Enter different numbers.

Now that we know it works, you will copy only the functions is_prime, and paste it in your code, then call it in the loop where you walk and check your array.

Finally, call is_prime in the loop, and if it returns false, set array position to 0.

I did an example with the button Check array. Test it.

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