mardi 3 mars 2015

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>




Aucun commentaire:

Enregistrer un commentaire