Hey cant work out whats wrong with my prime code, wondered if you can help
The code is meant to have two functions. the first to determine if an integer is prime the second to show all prime numbers between two integers. so far my first function works fine but I'm getting the error message "Uncaught TypeError: Property 'prime' of object [object Window] is not a function primefeat2-2.html:30" for the second function. cant for the life of me work out whats wrong would appreciate some help I will collaborate them to be two separate options after I have worked out the basic code.
<html>
<body>
<script type="text/javascript">
function prime(){
var count = 2;
var stop = Math.ceil(Math.sqrt(number1));
var remainder = number1 % count;
while(count < stop){
number1 % count;
if (remainder == 0){
prime = false;
break;
}
else{
prime = true;
}
count ++;
}
}
function feature2(){
var number1 = window.prompt("enter a number","0");
var number2 = window.prompt("enter a number","0");
while (number1 < number2){
if (prime(number1)){
document.writeln(+ number1 + " is prime");
}
number1++;
}
I worked it out and improved it a great deal so it works. Now i have to create another feature to work out the primes between 2 numbers. wish me luck (: got 3 days left
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