Do not use document.write (or writeln) which is made to write on an open document (at the opening of the page) but never when the document is fully loaded.
Use rather document.getElementById('rsp') in a script at the bottom of the body or after a onload event (the document should this time be present) to insert some html text with innerHTML with something like following.
Then its possible to avoid many divisions with only odd integers or the preceding primes which can be store in an array...
Code:
<body>
<div id="pge"></div>
<script type="text/javascript">
// An object
var Prm={
// with properties
nbr:null,prm:[2],rng:1,
// Initialization
ini:function(){Prm.nbr=3;Prm.prm[Prm.rng++]=3;
document.getElementById('pge').innerHTML='2, 3';
// The following !
Prm.svt();},
// Search with odd integers
svt:function(){
Prm.nbr+=2;
if (Prm.tst()) {document.getElementById('pge').innerHTML+=', '+Prm.nbr;
Prm.prm[Prm.rng++]=Prm.nbr;}
// The first 1000
if (Prm.rng<1000) setTimeout(Prm.svt,3);
},
// Prime test with the preceding primes
tst:function(){var i=0,j,m=~~Math.sqrt(Prm.nbr);
while(Prm.prm[i]<=m && (j=Prm.nbr%Prm.prm[i])!=0) i++;
return j!=0;
}
}
Prm.ini();
</script>
</body>
Other methods test only 6 x k +-1 integers. See other threads of is forum and particularly this rndme function isPrime.
Bookmarks